-1

I want to use subprocess.popen to start a serving,

start_predict = "nohup python predictor.py  --port 8086 &"
start_predict = start_predict.split(" ") 
subprocess.Popen(start_predict)

But it told me error: unrecognized arguments: &

and I need to add "&" because I need to see what happened.

david129
  • 13
  • 2
  • 2
    You don't need the "&" if you are starting the process directly. That's a shell option, and you're not using the shell here. – Tim Roberts Oct 09 '22 at 06:46
  • @TimRoberts I need to add "&",because I need to see the process. – david129 Oct 09 '22 at 06:48
  • No. That's only true if you have the shell starting the process. When you're calling this from Python, you are in control over whether you block for the results or just let it continue on. It's up to YOU to do what the shell does with `&`. – Tim Roberts Oct 09 '22 at 07:19

2 Answers2

0

Popen itself already does exactly what you are trying to accomplish; it starts a new process and allows it to run in parallel with your Python script.

In some more detail, you are apparently looking for something like

predictor = subprocess.Popen(
    ["python", "predictor.py", "--port", "8086"])
... # other python code here
result = predictor.communicate()

You'll need to take care of waiting for the process you started, so probably put the communicate (or wait etc) in the code which runs when your script finishes.

For what it's worth, & is a shell feature; you could accomplish the same thing more crudely and expensively by (taking out the split and) using shell=True; but you generally want to avoid that when you can. See also Actual meaning of shell=True in subprocess

Notice also that " ".split() is only suitable for the most trivial cases. You want to use shlex.split() instead; or, as here, simply manually split the command line into tokens yourself.

I seriously doubt that nohup makes sense here, so I took it out. It's usually not a great idea to run Python explicitly as a subprocess of itself; perhaps instead look into the multiprocessing library which lets you run an individual Python function in a separate process, with more fine-grained control over it.

tripleee
  • 175,061
  • 34
  • 275
  • 318
-1

You can use this code:

start_predict = "nohup python predictor.py  --port 8086 &"
subprocess.Popen(start_predict,shell=True)
Alex
  • 68
  • 4