0

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

2 Answers 2

2

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"], ...)
Sign up to request clarification or add additional context in comments.

3 Comments

thanks for reply, could you suggest how i can send input trough ’communicate()’ ? ex. send a test.js file for execution...
i guess communicate() closes the stdout, stdin and stderr once called...
@ElysMech Instead of communicate, you can use spawn.stdout, stdin, stderr, as regular streams.
0

We can also use python oS package to run opearting system command use os package popen method and read the output using read function

import os

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

output = stream.read()

print(output)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.