更新时间:2023-11-29 17:14:34
是的,如果您使用的是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.