在 Python 中,没有导入的命令行参数? [英] In Python, command line args without import?

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

问题描述

在 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

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

这篇关于在 Python 中,没有导入的命令行参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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