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

2024-06-16 10:16:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用一个只在bash中运行的科学软件(称为vasp),并使用Python创建一个可以为我多次运行的脚本。当我使用subprocess.check_调用要正常调用该函数,它可以正常工作,但当我添加'| tee_output'时,它就不起作用了。在

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

我对python和编程都很在行。在


Tags: 函数脚本bashoutput软件check编程科学
3条回答

你可以这样做:

vasp = subprocess.Popen('vasp', stdout=subprocess.PIPE)
subprocess.check_call(('tee', 'tee_output'), stdin=vasp.stdout)

这通常比使用shell=True更安全,尤其是当您不能信任输入时。在

注意,check_call将检查tee的返回码,而不是{},以确定它是否应该引发一个CalledProcessError。(shell=True方法将执行相同的操作,因为这与shell管道的行为相匹配。)如果需要,可以通过调用vasp.poll()自己检查vasp的返回代码。(另一种方法不允许您这样做。)

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

subprocess.check_call('vasp | tee tee_output', shell=True)

但请注意docs中有关此方法的警告。在

不要使用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()

我知道它比较长,但安全得多。在

相关问题 更多 >