检索 Python 解释器的命令行参数 [英] Retrieve the command line arguments of the Python interpreter

查看:34
本文介绍了检索 Python 解释器的命令行参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

受到另一个问题的启发,我想以可移植的方式检索 Python 解释器的完整命令行.也就是说,我想获得解释器的原始 argv,而不是 sys.argv,它排除了解释器本身的选项(如 -m>、-O 等).

Inspired by another question here, I would like to retrieve the Python interpreter's full command line in a portable way. That is, I want to get the original argv of the interpreter, not the sys.argv which excludes options to the interpreter itself (like -m, -O, etc.).

sys.flags 告诉我们设置了哪些布尔选项,但它没有告诉我们关于 -m 参数,并且标志集必然会随着时间的推移而改变,从而造成维护负担.

sys.flags tells us which boolean options were set, but it doesn't tell us about -m arguments, and the set of flags is bound to change over time, creating a maintenance burden.

在 Linux 上,您可以使用 procfs 来检索原始命令行,但这不可移植(而且有点粗糙):

On Linux you can use procfs to retrieve the original command line, but this is not portable (and it's sort of gross):

open('/proc/{}/cmdline'.format(os.getpid())).read().split('\0')

推荐答案

你可以使用 ctypes

You can use 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'

这篇关于检索 Python 解释器的命令行参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆