在Python中,没有导入的命令行参数? [英] In Python, command line args without import?
问题描述
在Python中,是否可以在不导入sys(或任何其他模块)的情况下获取命令行参数?
In Python, is it possible to get the command line arguments without importing sys (or any other module)?
推荐答案
是的,如果您使用的是Linux.
Yes, if you're using Linux.
如果知道进程ID,则可以读取其/proc/{pid}/cmdline
文件,该文件包含以空分隔的命令行参数列表:
If you know the process ID, you can read its /proc/{pid}/cmdline
file, which contains a null-separated list of the command line arguments:
PROCESS_ID = 14766
cmdline = open("/proc/" + str(pid) + "/cmdline").read()
print cmdline.split("\0")
但是在启动进程之前很难知道进程ID.但是有一个解决方案!查看所有过程!
But it's hard to know the process ID before you start the process. But there's a solution! Look at ALL of the processes!
PROGRAM_NAME = "python2\0stack.py"
MAX_PID = int(open("/proc/sys/kernel/pid_max").read())
for pid in xrange(MAX_PID):
try:
cmd = open("/proc/" + str(pid) + "/cmdline").read().strip("\0")
if PROGRAM_NAME in cmd:
print cmd.split("\0")
break
except IOError:
continue
因此,如果我们在外壳上运行python2 stack.py arg1 arg2 arg3
,将打印命令行参数列表.假设您在给定的时间只有一个进程运行脚本.
So if we run python2 stack.py arg1 arg2 arg3
at the shell, a list of the command line arguments will be printed. This assumes you only ever have one process running the script at a given time.
PS.,MAX_PID
是系统上的最大PID.您可以在/proc/sys/kernel/pid_max
中找到它.
PS., MAX_PID
is the maximum PID on your system. You can find it in /proc/sys/kernel/pid_max
.
PPS.永远不要,永远,永远编写这样的代码.这个帖子是49%的笑话.
PPS. Never, ever, ever write code like this. This post was 49% joke.
这篇关于在Python中,没有导入的命令行参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!