[英]How to automate running python code with every combination of command line options
我写了一些带有命令行选项的python代码。 我想自动运行每个组合,而不必手动键入所有组合。
目前,我有一个类似于以下内容的perl脚本(尽管具有更多选项,因此嵌套了更多foreach循环):
use Cwd;
$curdir=getcwd;
@opt1 = ("", "-s");
@opt2 = ("","-w \'binary\'", "-w \'tf\'", "-w \'tfidf\'") #There are arguments but there is a finite amount of them.
foreach $s (@opt1) {
foreach $t (@opt2) {
$cmd="python myCode.py $s $t";
system($cmd);
}
}
这导致以下代码正在运行python myCode.py -t 'binary'
, python myCode.py -t 'tf'
, python myCode.py -t 'tfidf'
, python myCode.py -s -t 'binary'
, python myCode.py -s -t 'tf'
, python myCode.py -s -t 'tfidf'
。
这似乎是一种可怕的方法(考虑到我实际上还有更多选择),是否有适当或更好的方法? 我愿意使用python来自动化它,我最初使用过perl,因为我有一个perl脚本可以调用其他程序。
您可以在python文件中执行此操作。 将所有内容包装在一个函数中,然后处理命令行参数的组合,例如:
import sys
import itertools
args = sys.argv[1:]
for i in range(len(args)+1):
for c in itertools.combinations(args, i):
print c # You'd put your function call here
使用mycode.py -a -b -c
, c
的迭代为:
() ('-a',) ('-b',) ('-c',) ('-a', '-b') ('-a', '-c') ('-b', '-c') ('-a', '-b', '-c')
使用mycode.py -a -b -c -d
, c
的迭代为:
() ('-a',) ('-b',) ('-c',) ('-d',) ('-a', '-b') ('-a', '-c') ('-a', '-d') ('-b', '-c') ('-b', '-d') ('-c', '-d') ('-a', '-b', '-c') ('-a', '-b', '-d') ('-a', '-c', '-d') ('-b', '-c', '-d') ('-a', '-b', '-c', '-d')
因此,您的代码可能如下所示:
import sys
import itertools
def your_function(args):
print("your_function called with args=%s" % str(args))
'''
SOME LONG FUNCTION HERE
'''
# Call your_function on all r-length combinations of command line arguments
# where 0 <= r <= len(args)
if __name__ == "__main__":
args = sys.argv[1:]
for i in range(len(args)+1):
for c in itertools.combinations(args, i):
your_function(c)
我建议您使用CPAN上Perl Algorithm::Combinatorics
模块中的combinations
功能。 它不是核心模块,因此可能需要安装。
use strict;
use warnings;
use Algorithm::Combinatorics qw/ combinations /;
my @switches = qw/ -a -b -c /;
for my $n ( 0 .. @switches ) {
for my $combination ( combinations(\@switches, $n) ) {
print join(' ', qw/ python myCode.py /, @$combination), "\n";
}
}
输出
python myCode.py
python myCode.py -a
python myCode.py -b
python myCode.py -c
python myCode.py -a -b
python myCode.py -a -c
python myCode.py -b -c
python myCode.py -a -b -c
这就是我最终要做的事情:
use Math::Cartesian::Product;
cartesian {system("python myCode.py @_")} ["","-s"], ["-w \'tf\'", "-w \'binary\'", "-w \'tfidf\'"];
在python中itertools.product做了我一直在寻找的东西:
import itertools
opts_list = [["","s"], ["tf","binary","tfidf"]]
print list(itertools.product(*opts_list))
印刷品:
[('', 'tf'), ('', 'binary'), ('', 'tfidf'), ('s', 'tf'), ('s', 'binary'), ('s', 'tfidf')]
我略微更改了代码以使用此方法,但我想可以将元组中的每个元素连接成一个字符串,以便在命令行中运行选项。
有关笛卡尔产品的答案应该可以在Python中为您解决问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.