Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running NodeJS from Python

Tags:

python

node.js

I'm having a tough time figuring out how to run NodeJS from Python. I have no problems running ShellScript from Python and NodeJS from ShellScript, but can't seem to get NodeJS from Python, I just get the following output:

b"

These are the simplified version of my scripts.

NodeJS I am trying to run from within Python.

#!/usr/bin/env node
console.log("Hello " + process.argv[2]);

And here is the Python, using Python3.

from datetime import datetime
import json
import os
import re
import sys
import subprocess

if __name__ == '__main__':
        p = subprocess.Popen(['/Users/Brett/scripts/hello.js', 'Brett'], stdout=subprocess.PIPE)
        out = p.stdout.read()
        print(out)
        

Thanks for the help! Much appreciated.

EDITS: I have no issue executing the following from the commandline, as 'hello.js' is executable:

hello.js 'Brett'

shell=true does not fix it.

Additionally, I am on macOS Catalina 10.15.5 and therefore my shell is zsh.

If I add node to the front of the command, I get no such file or directory for node, I tried it as follows: p = subprocess.Popen(['/Users/Brett/scripts/hello.js', 'Brett'], stdout=subprocess.PIPE)

like image 387
Brett Avatar asked Sep 03 '26 22:09

Brett


1 Answers

Thanks everyone for the responses. All were super helpful. Especially @max-stanley and @jared-smith.

The following ended up working for me:

p = subprocess.Popen(['/usr/local/bin/node', '/Users/Brett/scripts/hello.js', 'Brett'], stdout=subprocess.PIPE)
out = p.stdout.read()
print(out)

Not sure why it doesn't work with the shebang in the executable js file but I am not committed to it, so I will just take the working solution and move on. ;-)

Cheers!

like image 107
Brett Avatar answered Sep 06 '26 13:09

Brett



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!