1

I'm sorry if this question is a dupe, but I looked at this post and this post, yet was still unable to find a solution.

I just want to execute the following bash command in my Python script to get the current epoch timestamp integer via NodeJS:

node -e "console.log(Date.now());"

The output is as expected, but when I run this in Python:

nodejs_list = ["node", "-e", '"console.log(Date.now());"']
node_time = subprocess.run(
    nodejs_list,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    text=True
)
print(node_time)

All I'm able to get is the CompletedProcess() output, but not the time integer:

CompletedProcess(args=['node', '-e', '"console.log(Date.now());"'], returncode=0, stdout='', stderr='')

I've even tried:

subprocess.run(nodejs_list, capture_output=True, text=True).stdout.strip("\n")

And:

subprocess.check_output(nodejs_list)

But these don't return what I need either.

I'm assuming it's because Python is unable to capture the output of Node's console.log() or something. Is there someway to "flush" the NodeJS output? What am I doing wrong here?

Benji
  • 310
  • 3
  • 12

1 Answers1

1

When you run this node -e "console.log(Date.now());" in terminal, it is working. Bash shell will accept this without any problem. NodeJs will execute console.log(Date.now());, and this will produce an output to stdout

But you use extra quotes in subprocess.run func, and this causing '"console.log(Date.now());"' interpreted as a string like "console.log(Date.now());" in NodeJs. That's why, NodeJs does not produce any output. To solve this, we can do like below ;

nodejs_list = ["node", "-e", "console.log(Date.now());"]
node_time = subprocess.run(
    nodejs_list,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    text=True
)
print(node_time.stdout.strip())

You can also check this

Veysel Olgun
  • 552
  • 1
  • 3
  • 15