【问题标题】:send input through stdin in python subprocess.popen在 python subprocess.popen 中通过标准输入发送输入
【发布时间】:2021-03-05 05:58:17
【问题描述】:

我想通过 subprocess 模块启动 nodejs 并向其发送输入但遇到以下错误...

代码:

import subprocess
def popen(self):
    cmd = "node"
    args = "--version"
    spawn = subprocess.Popen(cmd,shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    (out,err)=spawn.communicate(args)
    print(out)
    print(err)

结果:

    [stdin]:1
--version
^

ReferenceError: version is not defined
    at [stdin]:1:1
    at Script.runInThisContext (vm.js:132:18)
    at Object.runInThisContext (vm.js:309:38)
    at internal/process/execution.js:77:19
    at [stdin]-wrapper:6:22
    at evalScript (internal/process/execution.js:76:60)
    at internal/main/eval_stdin.js:29:5
    at Socket.<anonymous> (internal/process/execution.js:198:5)
    at Socket.emit (events.js:327:22)
    at endReadableNT (_stream_readable.js:1327:12)

预期结果:

v14.14.0

基本上,我想启动节点并与之通信,在需要时发送输入。

为了更好地控制进程而选择了 Popen 而不是运行,并且 shell 设置为 true,因此操作系统变量被视为 ex。 $路径

【问题讨论】:

    标签: python python-3.x subprocess stdin communicate


    【解决方案1】:

    此代码相当于您开始 node,然后输入 --version 并按 Enter。这样,node 将尝试将其解释为 JavaScript 语句,并且它无法识别名称 version。相反,您应该将其作为命令行参数传递:

    subprocess.Popen(["node", "--version"], ...)
    

    【讨论】:

    • 感谢您的回复,您能建议我如何通过 'communicate()' 发送输入吗?前任。发送一个 test.js 文件执行...
    • 我猜communicate() 会关闭标准输出、标准输入和标准错误一次调用...
    • @ElysMech 代替communicate,您可以使用spawn.stdoutstdinstderr 作为常规流。
    【解决方案2】:

    我们也可以使用python os包来运行操作系统命令 使用os包popen方法并使用read函数读取输出

    代码:

    导入操作系统

    stream = os.popen('node --version')

    输出 = stream.read()

    打印(输出)

    【讨论】:

      猜你喜欢
      • 2011-11-30
      • 2014-03-04
      • 1970-01-01
      • 1970-01-01
      • 2015-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多