Saurabh Singhai
Saurabh Singhai

Reputation: 318

Python: Unable to start the JSON server using subprocess.run

Objective : To start the JSON server from windows command prompt using python and verify that it has actually started by checking the string like "http://localhost:3000" (see the command output from the screenshot) image.png

Problem Identified: Since the command is not returning anything therefore I am unable to validate anything. What can be a possible solution or a workaround for this?

Code Written :

I have tried using :

ret = subprocess.run('json-server --port 3000 --watch db.json', shell=True)

Also, tried following methods from subprocess and os classes

subprocess.call
subprocess.check_output
os.system

Upvotes: 1

Views: 276

Answers (1)

rokpoto.com
rokpoto.com

Reputation: 10778

Use subprocess.Popen for staring json-server as child program in a new process. And then validate it's started by sending http request to localhost:3000.

Starting the server:

import subprocess
from signal import SIGKILL

p = subprocess.Popen('json-server --port 3000 --watch /tmp/db.json', shell=True)

# printing output of json-server
try:
    outs, errs = p.communicate(timeout=15)
    print(outs)
except subprocess.TimeoutExpired:
    p.send_signal(SIGKILL)
    outs, errs = p.communicate()

Sending validation request:

import urllib.request
with urllib.request.urlopen("http://localhost:3000") as res:
    print(res.status)

Note that json-server is daemon process and doesn't stop until you stop it, kill it or it stumbles on unexpected exception.

So it will be running after you execute this code unless you stop in Python code or windows process explorer.

Upvotes: 1

Related Questions