如何在Python中获得OS的argv[0](而不是sys.argv[0]) ?

时间:2021-09-02 23:03:19

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

我想在Python程序中获取操作系统argv[0]的真实值。Python的系统。argv[0]不是这个值:它是正在执行的Python脚本的名称(有一些例外)。我想要的是foo。当执行为时,将打印“somestring”

exec -a "somestring" python foo.py

The trivial program

琐碎的程序

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

will print "foo.py" instead.

将打印“foo。py”。

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?

有人知道怎么得到这个吗?在Python C API中有一些相关的函数:例如Py_GetProgramName。但在任何地方,这似乎都不会暴露给Python世界。Py_GetProgramFullPath在argv[0]上工作,但是修改它以获得一个Python解释器的路径。(此值传播给sys。可执行的,所以这个变量也不对)我真的需要编写一个C模块来获取这个值吗?

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

编辑:在这里也被问到(但没有得到帮助)。

1 个解决方案

#1


7  

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

在Linux上,您可以阅读/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.

当解释器退出后,在bash中似乎存在一个错误,exec命令将替换关闭终端会话的shell。这是第一次抨击。

#1


7  

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

在Linux上,您可以阅读/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.

当解释器退出后,在bash中似乎存在一个错误,exec命令将替换关闭终端会话的shell。这是第一次抨击。