我正在使用一个只能在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和编程的新手。
发布于 2012-03-08 05:32:50
尝尝这个。它通过shell执行命令(作为字符串传递),而不是直接执行命令。(这相当于使用-c标志调用外壳本身,即Popen(['/bin/sh', '-c', args[0], args[1], ...])):
subprocess.check_call('vasp | tee tee_output', shell=True)但请注意docs中有关此方法的警告。
发布于 2012-03-08 06:00:50
你可以这样做:
vasp = subprocess.Popen('vasp', stdout=subprocess.PIPE)
subprocess.check_call(('tee', 'tee_output'), stdin=vasp.stdout)这通常比使用shell=True更安全,特别是在您不能信任输入的情况下。
请注意,check_call将检查tee的返回码,而不是vasp的返回码,以查看是否应该引发CalledProcessError。( shell=True方法将执行相同的操作,因为这与外壳管道的行为相匹配。)如果需要,您可以通过调用vasp.poll()来自己检查vasp的返回码。(另一种方法不允许您这样做。)
发布于 2012-03-08 06:13:59
不要使用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()我知道它更长,但它更安全。
https://stackoverflow.com/questions/9609375
复制相似问题