问题
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