您可以使用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'
>>> argv[0]
现在是 b'p'
。 - szmoore我会再添加一个答案。 @bav的答案适用于Python 2.7,但正如@szmoore所指出的那样,在Python 3中会出现问题(不仅限于3.7)。然而,下面的代码将在Python 2和Python 3中都有效(这是因为Python 3中的c_wchar_p
而不是Python 2中的c_char_p
),并且会正确地将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
你会注意到它仅返回解释器参数,而排除了在 sys.argv
中找到的参数。您可以通过删除 - len(sys.argv) + 1
来消除这种行为。
*argc
和**argv
做任何其他操作。虽然有Py_GetArgcArgv,但我没有在文档化的C-API中找到它的任何应用... - mgilson.split('\0')
比.replace('\0', ' ')
更加正确--否则无法区分包含空格的参数和独立的参数。 - tripleee