如何在python中使用|调用多个bash函数

如何在python中使用|调用多个bash函数,python,bash,call,subprocess,Python,Bash,Call,Subprocess,我正在使用一个只在bash中工作的科学软件(称为vasp),并使用Python创建一个脚本,该脚本将为我进行多次运行。当我使用subprocess.check_call正常调用函数时,它工作正常,但当我添加“| tee tee_output”时,它不工作 subprocess.check_call('vasp') #this works subprocess.check_call('vasp | tee tee_output') #this doesn't 我是python和编程的高手 试试这

我正在使用一个只在bash中工作的科学软件(称为vasp),并使用Python创建一个脚本,该脚本将为我进行多次运行。当我使用subprocess.check_call正常调用函数时,它工作正常,但当我添加“| tee tee_output”时,它不工作

subprocess.check_call('vasp') #this works
subprocess.check_call('vasp | tee tee_output') #this doesn't

我是python和编程的高手

试试这个。它通过shell执行命令(作为字符串传递),而不是直接执行命令。(这相当于使用
-c
标志调用shell本身,即
Popen(['/bin/sh','-c',args[0],args[1],…])
):

但是请注意中关于此方法的警告。

您可以这样做:

vasp = subprocess.Popen('vasp', stdout=subprocess.PIPE)
subprocess.check_call(('tee', 'tee_output'), stdin=vasp.stdout)
这通常比使用
shell=True
更安全,尤其是当您不能信任输入时


请注意,
check\u call
将检查
tee
的返回代码,而不是
vasp
,以查看它是否应引发
调用的进程错误。(shell=True
方法将执行相同的操作,因为这与shell管道的行为相匹配。)如果需要,可以通过调用
vasp.poll()
自己检查
vasp
的返回代码。(另一种方法不允许您这样做。)

不要使用shell=True,它有许多安全漏洞。相反,你可以这样做

cmd1 = ['vasp']
cmd2 = ['tee', 'tee_output']

runcmd = subprocess.Popen(cmd1, stdout=subprocess.PIPE)
runcmd2 = subprocess.Popen(cmd2, stdin=runcmd.stdout, stdout=subprocess.PIPE)

runcmd2.communicate()

我知道它更长,但更安全。

您可以在文档中找到更多信息:


只需在
t
object

@user1255726:It.@user1255726,我相信你的话,你的软件“只在bash中工作”。如果这不是真的,那么出于安全原因,其他答案之一更可取。如果是这样,请告诉我。
cmd1 = ['vasp']
cmd2 = ['tee', 'tee_output']

runcmd = subprocess.Popen(cmd1, stdout=subprocess.PIPE)
runcmd2 = subprocess.Popen(cmd2, stdin=runcmd.stdout, stdout=subprocess.PIPE)

runcmd2.communicate()