Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python sys.executable is empty

Tags:

python

execve

I am testing out doing some shenanigans with os.execve and virtual environments. I am running into the problem where sys.executable is empty if I replace the current python process with another python subprocess.

The example below shows what's going on (run this inside a python shell):

import os, sys
print(sys.executable) # works this time
os.execve("/usr/bin/python", [], {}) # drops me into a new python shell
import sys # yes, again
print(sys.executable) # is empty

The full output of me running the commands above in a python shell:

 lptp [ tmp ]: python
Python 2.7.10 (default, Oct 14 2015, 16:09:02) 
[GCC 5.2.1 20151010] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os, sys
>>> print(sys.executable) # works this time
/usr/bin/python
>>> os.execve("/usr/bin/python", [], {}) # drops me into a new python shell
Python 2.7.10 (default, Oct 14 2015, 16:09:02) 
[GCC 5.2.1 20151010] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys # yes, again
>>> print(sys.executable) # is empty

>>>

sys.executable being empty is causing me problems, most notably that platform.libc_ver() fails because sys.executable is empty:

>>> import platform
>>> platform.libc_ver()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/platform.py", line 163, in libc_ver
    f = open(executable,'rb')
IOError: [Errno 21] Is a directory: '/tmp'

Note that the example above was run after calling os.execve(...)

like image 829
d0c_s4vage Avatar asked Aug 31 '16 16:08

d0c_s4vage


1 Answers

Python relies on argv[0] and several environment variables to determine sys.executable. When you pass an empty argv and environment, Python doesn't know how to determine its path. At the very least, you should provide argv[0]:

os.execve('/usr/bin/python', ['/usr/bin/python'], {})
like image 88
user2357112 supports Monica Avatar answered Oct 01 '22 11:10

user2357112 supports Monica