[英]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.