且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Python 中,没有导入的命令行参数?

更新时间:2023-11-29 17:06:28

是的,如果您使用的是 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

因此,如果我们在 shell 中运行 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.