Joh*_*nck 17 python command-line argv command-line-arguments
受到另一个问题的启发,我想以便携方式检索Python解释器的完整命令行.也就是说,我想原来argv解释的,而不是sys.argv不包括选项来解释本身(如-m,-O等).
sys.flags告诉我们设置了哪些布尔选项,但它没有告诉我们有关-m参数的信息,并且标志集必然会随着时间的推移而发生变化,从而产生维护负担.
在Linux上,您可以使用procfs来检索原始命令行,但这不是可移植的(并且它有点粗略):
open('/proc/{}/cmdline'.format(os.getpid())).read().split('\0')
Run Code Online (Sandbox Code Playgroud)
小智 12
你可以使用ctypes
~$ python2 -B -R -u
Python 2.7.9 (default, Dec 11 2014, 04:42:00)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Persistent session history and tab completion are enabled.
>>> import ctypes
>>> argv = ctypes.POINTER(ctypes.c_char_p)()
>>> argc = ctypes.c_int()
>>> ctypes.pythonapi.Py_GetArgcArgv(ctypes.byref(argc), ctypes.byref(argv))
1227013240
>>> argc.value
4
>>> argv[0]
'python2'
>>> argv[1]
'-B'
>>> argv[2]
'-R'
>>> argv[3]
'-u'
Run Code Online (Sandbox Code Playgroud)
我将为此添加另一个答案。@bav为Python 2.7提供了正确的答案,但正如@szmoore指出的那样,它在Python 3中不起作用(不仅仅是3.7)。但是,下面的代码将在Python 2和Python 3中都可以使用(其关键是c_wchar_p在Python 3中,而不是c_char_p在Python 2中),并将正确地转换argv为Python列表,以便可以安全地在其他Python代码中使用而无需段故障:
def get_python_interpreter_arguments():
argc = ctypes.c_int()
argv = ctypes.POINTER(ctypes.c_wchar_p if sys.version_info >= (3, ) else ctypes.c_char_p)()
ctypes.pythonapi.Py_GetArgcArgv(ctypes.byref(argc), ctypes.byref(argv))
# Ctypes are weird. They can't be used in list comprehensions, you can't use `in` with them, and you can't
# use a for-each loop on them. We have to do an old-school for-i loop.
arguments = list()
for i in range(argc.value - len(sys.argv) + 1):
arguments.append(argv[i])
return arguments
Run Code Online (Sandbox Code Playgroud)
您会注意到,它也仅返回解释器参数,并排除了中的增强sys.argv。您可以通过删除消除此行为- len(sys.argv) + 1。
| 归档时间: |
|
| 查看次数: |
766 次 |
| 最近记录: |