0

I have the following lines:

#!/root/p34/bin/python 
import os
import sys

for i in range(10):
    print(i)

currentFile = os.path.abspath(__file__)
print(currentFile)  
os.execv(currentFile, sys.argv)

When I try to run from console(Ubuntu 14.04) ./restart.py I get:

': [Errno 2] No such file or directory'

When I run /root/p34/bin/python restart.py I get python error:

Traceback (most recent call last):
  File "restart.py", line 10, in <module>
    os.execv(currentFile, sys.argv)
FileNotFoundError: [Errno 2] No such file or directory

Can anyone help me with this problem?

Adrian B
  • 1,490
  • 1
  • 19
  • 31

1 Answers1

3

os.execv does not look for shebang lines; that is a shell function instead.

Use sys.executable to get the path to the current Python binary:

os.execv(sys.executable, [sys.executable] + sys.argv)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 1
    is it so that the `[sys.exectubale]` prepend is required because of the 'OS-level' 'argv replacement', so to speak? – n611x007 Aug 13 '15 at 15:18
  • 3
    @naxa: `os.execv` passes the arguments to the executable, and the first argument *must* be the name of the executable. Many UNIX tools rely on that to alter behaviour based on what symlink was used to execute the tool, for example. – Martijn Pieters Aug 13 '15 at 15:20
  • 1
    @naxa: In other words, you can pass in any string you like, but not all programs will like having something weird passed in. – Martijn Pieters Aug 13 '15 at 15:21
  • thanks! do you happen to have a historical hint on whether there was a time when programmers did not realize that they lack a way for the loaded program image to identify itself, and used exec*/argv differently? It seems like a convention and it's rather strange it's not structural! (I suspect C for popularizing the convention.) – n611x007 Aug 13 '15 at 15:32
  • 1
    @naxa: [Is "argv\[0\] = name-of-executable" an accepted standard or just a common convention?](http://stackoverflow.com/q/2050961) – Martijn Pieters Aug 13 '15 at 15:55