开发者

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.

Doe开发者_运维知识库s 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜