pkgw
pkgw

Reputation: 93

How can you obtain the OS's argv[0] (not sys.argv[0]) in Python?

I want to obtain the true value of the operating system's argv[0] in a Python program. Python's sys.argv[0] is not this value: it is the name of the Python script being executed (with some exceptions). What I want is a foo.py that will print "somestring" when executed as

exec -a "somestring" python foo.py

The trivial program

#! /usr/bin/env python
import sys
print sys.argv[0]

will print "foo.py" instead.

Does anyone know how to obtain this? There are some related functions in the Python C API: e.g. Py_GetProgramName. But this doesn't seem to be exposed to the Python world anywhere. Py_GetProgramFullPath works off of argv[0] but munges it try to obtain a path to a Python interpreter. (This value is propagated to sys.executable, so that variable isn't right either.) Do I really have to write a C module to get this value?

Edit: Also asked (but not helpfully answered) here.

Upvotes: 9

Views: 1090

Answers (1)

vz0
vz0

Reputation: 32923

On Linux you can read the contents of /proc/self/cmdline:

#!/usr/bin/env python
import sys
print sys.argv[0]

f = open('/proc/self/cmdline', 'rb')
cmdline = f.read()
f.close()

print repr(cmdline.split('\x00'))

And the output is:

$ bash
$ exec -a "somestring" python foo.py 
foo.py
['somestring', 'foo.py', '']

There seems to be a bug in bash The exec command replaces the shell closing the terminal session after the interpreter exits. That's the first bash for.

Upvotes: 7

Related Questions