【问题标题】:python: string as stdin to subcommandpython:字符串作为子命令的标准输入
【发布时间】:2016-02-08 01:06:42
【问题描述】:

我有一个 python 脚本,我需要在其中调用一个 shell 命令。 shell 命令可以接受来自文件或标准输入的输入。

在我的脚本中,输入存储在一个变量中。调用命令的正确方法是什么?如果重要,shell 命令不会产生任何输出。

我知道我可以将变量的内容写入文件并以文件作为参数调用命令,但这似乎不太优雅。当然,有更好的方法。

谁能告诉我它是什么?谢谢。

【问题讨论】:

标签: python shell


【解决方案1】:

您可以使用subprocess 模块。

import subprocess
process = subprocess.Popen(["Mycommand", "with", "arguments"], stdin=subprocess.PIPE)
process.communicate("My text")

【讨论】:

  • “使用communicate() 而不是.stdin.write、.stdout.read 或.stderr.read 以避免由于任何其他操作系统管道缓冲区填满并阻塞子进程而导致的死锁。” (来自docs.python.org/2/library/subprocess.html
  • @palvarez89 好电话。我修好了。
  • communicate() 是一种一次性方法。为了反复这样做,我从它的实现中复制了一些代码,这些代码在单独的线程中处理stdin
  • @ivan_pozdeev 我的回答确实使用了process.stdin.write,但正如palvarez89 提到的,这不是首选方式。 OP提到试图write the variable's content into a file and invoke the command with the file as argument。如果使用一次性方法存在问题,则不会建议这样做。
【解决方案2】:

参考How do I pass a string into subprocess.Popen (using the stdin argument)?

对于python 3.5+(编码为3.6+),可以使用input:

from subprocess import check_output   
output = check_output(["cat","-b"],
        input="-foo\n-bar\n-foobar", encoding='ascii')
print(output)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-04
    • 2014-08-19
    • 1970-01-01
    • 2019-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    相关资源
    最近更新 更多