使用python、Ubuntu操作系统从脚本调用命令行

使用python、Ubuntu操作系统从脚本调用命令行,python,bioinformatics,Python,Bioinformatics,我在从脚本调用命令行时遇到困难。我运行了脚本,但没有得到任何结果。通过脚本中的这个命令行,我想运行一个工具,该工具生成一个文件夹,其中包含每行的输出文件。你能帮帮我吗 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(),outputfold

我在从脚本调用命令行时遇到困难。我运行了脚本,但没有得到任何结果。通过脚本中的这个命令行,我想运行一个工具,该工具生成一个文件夹,其中包含每行的输出文件。你能帮帮我吗

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)
os.system(cmd)


您确实希望使用Python标准库模块。使用该模块中的函数,您可以将命令行构造为字符串列表,每个字符串将作为一个文件名、选项或值进行处理。这绕过了shell的转义,并且消除了在调用之前对脚本参数进行按摩的需要


此外,您的代码无法工作,因为
for
语句的主体块没有缩进。Python根本不接受这段代码(可以在没有适当缩进的情况下粘贴到questiong中)。

如前所述,不建议通过os.system(command)执行命令。请使用subprocess(阅读python文档中有关此模块的内容)。请参见此处的代码:

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

对于静态命令,我通常这样做

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/')
但这并不安全!!!你应该做的外壳注射是可以避免的

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,因此管道等将工作。当我有一个带有管道的大型命令行时,我会使用它,这是静态的,我的意思是,它不依赖于用户输入。这是因为这个变体对shell注入是脆弱的,用户可以输入
一些东西;rm-rf/
,它将运行

第二个变量只接受一个命令,它不会生成shell,而是直接运行该命令。因此,没有管道和类似外壳的东西可以工作,而且更安全

universal\u newlines=True
用于将输出作为字符串而不是字节。如果您需要二进制输出,请将其用于文本输出。默认值为false

下面是完整的例子

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:我没有测试这个

我也像调用一样尝试过(cmd,shell=True)