python - 子流程中的变量

标签 python python-2.7 subprocess

有没有办法在子进程中传递变量?这不起作用。

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/

相关文章:

windows - python cythonize 期间出现 "Intel\iCLS was unexpected"错误

python - 如何格式化 subprocess.call() 语句?

python - 在迁移文件中正确声明空 Django PostgreSQL JSONField 默认值

python - 让 Celery 使用 Django 测试数据库

python - plotly 破折号: how to draw y axis in different ticks?

python - 我可以使用单个 python 脚本来创建 virtualenv 并安装 requirements.txt 吗?

python - 通过 Python 子进程传递包含 % 的 ffmpeg 命令

python - Django休息框架: Could not resolve URL for hyperlinked relationship using view name "post-detail"

python - 如何在 Django ORM 中连接两个表而没有第一个表中的任何列引用第二个

python - bisect_left 和 bisect_right 什么时候不相等?