In args command line python without import?

In Python, can I get command line arguments without importing sys (or any other module)?

-2
source share
4 answers

Yes, if you are using Linux.

If you know the process identifier, you can read its file /proc/{pid}/cmdline, which contains a list of command line arguments separated by zeros:

PROCESS_ID = 14766
cmdline = open("/proc/" + str(pid) + "/cmdline").read()
print cmdline.split("\0")

But it’s hard for you to find out the process ID before you start the process. But there is a solution! Look at ALL 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 , . , - script .

PS., MAX_PID - PID . /proc/sys/kernel/pid_max.

. , , - . 49% .

+7

. sys, sys.argv,

+1

. sys.argv sys.
, sys?

+1

Linux , , sys.argv:

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

All Articles