1

I am trying to execute this:

os.execv(sys.executable, ['python'] + sys.argv)

The result I am getting:

C:\Program Files\Python310\python.exe: can't find '__main__' module in 'c:\\Users\\user\\OneDrive\\Рабочий'

As you can see, the path after the 'module in' words is improper. I printed sys.argv and got:

c:/Users/user/OneDrive/Рабочий стол/myfolder/file.py

1 Answers1

2

This is how to os.execv into another program passed in the command line:

# as execv_argv.py
import os
import sys

os.execv(sys.executable, [sys.executable] + sys.argv[1:])

and call with

python execv_argv.py "second exec.py"

Note os.execv with full sys.argv will call the parent again forever.

ljmc
  • 4,830
  • 2
  • 7
  • 26
  • Well actually i was trying to restart the same file after getting update event from watchdog, thank you for the answer – Michael Townley Aug 18 '22 at 15:53
  • replacing my execv with yours didn't help, it is now searching for wrong directory – Michael Townley Aug 18 '22 at 15:55
  • My `execv_argv.py` and the other executable are in the same directory, I don't know where your function that would call `execv` is compared to your main file. – ljmc Aug 18 '22 at 15:56
  • Plus if the watchdog finds an error with your program, then I would not recommend having the same program restart itself, have something else kick it back up. – ljmc Aug 18 '22 at 15:57
  • I am using vscode to start my file using: & "C:/Program Files/Python310/python.exe" "c:/Users/user/OneDrive/Рабочий стол/folder/onchange.py" – Michael Townley Aug 18 '22 at 16:14
  • Ok, can I use subprocess.call instead? Will it replace current process? – Michael Townley Aug 18 '22 at 16:20
  • `subprocess` will launch a new process not replace the current one, but this scheduling and replacement is sounding more and more like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – ljmc Aug 18 '22 at 16:23
  • Then how can I restart the script(like uvicorn or gunicorn) on file change? – Michael Townley Aug 18 '22 at 16:26
  • You mean like [gunicorn's `--reload` flag](https://docs.gunicorn.org/en/stable/settings.html#reload) or [uvicorn's `--reload` flag](https://www.uvicorn.org/settings/#development) ? – ljmc Aug 18 '22 at 16:28
  • Yeah, i wanted to implement something similar – Michael Townley Aug 18 '22 at 16:32
  • You should probably start by having a look at what they are doing, since neither of them is using `os.exec*` functions. https://github.com/benoitc/gunicorn/blob/master/gunicorn/reloader.py https://github.com/encode/uvicorn/tree/master/uvicorn/supervisors – ljmc Aug 18 '22 at 16:38