Search code examples
pythonpython-3.xsubprocessstdin

send input through stdin in python subprocess.popen


I would like to start nodejs through subprocess module and send input to it but facing below error...

code:

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)

Result:

    [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)

Expected Result:

v14.14.0

basically, i want to start node and communicate with it, send input as and when required.

Popen is chose instead of run for better control over process and shell is set to true so OS variables are considered ex. $PATH


Solution

  • This code is equivalent to you starting node, then typing --version and pressing enter. This way, node will try to interpret it as a JavaScript statement, and it does not recognize the name version. Instead, you should pass it as a command line argument:

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