有没有办法在子进程中传递变量?这不起作用。
subprocess.check_output(["cat test.txt | grep %s"], shell=True) %(variable)
最佳答案
您可以使用str.format
:
"cat test.txt | grep {}".format(variable)
或者使用旧式格式将变量直接放在后面。
"cat test.txt | grep %s"%variable
使用 shell=True 时,您的列表也是多余的:
subprocess.check_output("cat fable.txt | grep %s" %variable, shell=True)
如果您使用的参数列表没有 shell = True,则可以使用 Popen:
from subprocess import Popen,PIPE
p1 = Popen(["cat","text.txt"], stdout=PIPE)
p2 = Popen(["grep", variable], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()
out,err = p2.communicate()
p1.wait()
print(out)
关于python - 子流程中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28602550/