In Python, command line args without import?

烂漫一生 提交于 2019-12-25 19:04:49

问题


In Python, is it possible to get the command line arguments without importing sys (or any other module)?


回答1:


Yes, if you're using Linux.

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")

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

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 is the maximum PID on your system. You can find it in /proc/sys/kernel/pid_max.

PPS. Never, ever, ever write code like this. This post was 49% joke.




回答2:


No. You must import sys to get sys.argv, which is where the arguments are located




回答3:


No. Command line arguments are available only in sys.argv which cannot be accessed without importing sys.
May I ask why do you not want to import sys?




回答4:


On Linux, this will give you an array identical to the one that sys.argv would return:

argv = open('/proc/self/cmdline').read().split('\0')


来源:https://stackoverflow.com/questions/27368283/in-python-command-line-args-without-import

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!