简体   繁体   中英

How to restart Python 3.5 script with space in path in Windows

I need to implement a function that can restart the Python script on demand. A loop in the main is not acceptable. Both the Python executable and the script contain spaces.

What I've tried:

python = sys.executable
os.execl(python, python, * sys.argv)

Fails because the path contain spaces: C:\\Program: can't open file 'Files': [Errno 2] No such file or directory

python = '"' + sys.executable + '"'
os.execl(python, python, * sys.argv)

It fails with

OSError: [Errno 22] Invalid argument

Simply:

os.execl(python, python)

Fails as well.

I've also tried:

subprocess.run([python])

And fails with: PermissionError: [WinError 5] Access is denied

subprocess.run(['"' + python + '"'])
subprocess.run(['""' + python + '""'])

Also fails...

Thank you for your help

Solved it with Popen:

    python = sys.executable
    script = os.path.realpath(__file__)
    subprocess.Popen([python, script])

If you do end up needing to use os.execl the following should work

python = sys.executable
os.execl(python, '"' + python + '"', *sys.argv)

The quotes should solve any issues due to any spaces in the path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM