gpt4 book ai didi

python - 将管道与 python "subprocess"模块一起使用

转载 作者:行者123 更新时间:2023-11-30 23:29:13 25 4
gpt4 key购买 nike

假设我想在 Windows 批处理文件中调用程序theprogram。代码如下所示:

exit | theprogram arg1

我已经测试过了,效果非常好,非常感谢!

现在,策略发生了重大变化,我必须在 python 脚本中调用程序。为此,我使用子进程模块。我得到:

subprocess.call(['theprogram', arg1])

但是为了使其正常工作,我需要使用 exit 语句来进行管道传输,就像我在批处理文件中所做的那样。当然,这行不通

subprocess.call(['exit | theprogram', arg1])

有谁知道如何正确地将这个 exit 语句传递到 theprogram 的输入?

非常感谢!

最佳答案

指定 shell 关键字参数以通过 shell 解析调用:

subprocess.call('exit | theprogram %s' % arg1, shell=True)

当然,如果 arg1 包含空格或其他 shell 的元字符,这会强制您手动引用它。通常情况下,subprocess.call 不会精确调用 shell,因此您不必担心引用问题,但在您的情况下,它会把婴儿和洗澡水一起扔掉,因为您想要 shell 帮助管道操作符工作。

一个保留两全其美的更好的替代方案,但以一些打字为代价,是允许 subprocess 模块设置管道:

p1 = subprocess.Popen(["exit"], stdout=subprocess.PIPE)
p2 = subprocess.Popen(["theprogram", arg1], stdin=p1.stdout)
p1.stdout.close()
p2.communicate()

现在您不需要 shell,也无需担心引用。 the documentation 中提供了使用 subprocess 模块的更多示例。 .

关于python - 将管道与 python "subprocess"模块一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21236489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com