3 回答

TA貢獻1829條經驗 獲得超7個贊
您真的想使用 Python 標準庫模塊subprocess。使用該模塊中的函數,您可以將命令行構建為字符串列表,并且每個字符串都將作為一個文件名、選項或值進行處理。這繞過了 shell 的轉義,并消除了在調用之前對腳本參數進行按摩的需要。
此外,您的代碼將不起作用,因為for
語句的主體塊沒有縮進。Python 根本不會接受此代碼(您可能會在沒有適當縮進的情況下粘貼到 questiong 中)。

TA貢獻1841條經驗 獲得超3個贊
我通常對靜態命令這樣做
from subprocess import check_output
def sh(command):
return check_output(command, shell=True, universal_newlines=True)
output = sh('echo hello world | sed s/h/H/')
但這不安全?。?!你應該做的shell注入很容易
from subprocess import check_output
from shlex import split
def sh(command):
return check_output(split(command), universal_newlines=True)
output = sh('echo hello world')
差異是微妙但重要的。shell=True 將創建一個新的外殼,因此管道等將起作用。當我有一個帶有管道的大命令行并且是靜態的時,我會使用它,我的意思是,它不依賴于用戶輸入。這是因為這個變體對 shell 注入很敏感,用戶可以輸入something; rm -rf /并且它會運行。
第二種變體只接受一個命令,它不會生成 shell,而是直接運行命令。所以沒有管道和這樣的外殼會起作用,而且更安全。
universal_newlines=True用于將輸出作為字符串而不是字節。將它用于文本輸出,如果您需要二進制輸出,只需省略它。默認值為假。
所以這是完整的例子
from subprocess import check_output
from shlex import split
def sh(command):
return check_output(split(command), universal_newlines=True)
for line in inputFile:
cmd = 'python3 CRISPRcasIdentifier.py -f %s/%s.fasta -o %s/%s.csv -st dna -co %s/'%(inputpath,line.strip(),outputfolder,line.strip(),outputfolder)
sh(cmd)
ps:我沒有測試這個

TA貢獻1862條經驗 獲得超7個贊
如前所述,不推薦執行命令 vias: os.system(command)。請使用 subprocess (在 python 文檔中閱讀有關此模塊subprocess_module_docs)。在這里查看代碼:
for command in input_file:
p = subprocess.Popen(command, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
# use this if you want to communicate with child process
# p = subprocess.Popen(command, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
p.communicate()
# --- do the rest
添加回答
舉報