Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass arguments to a module in python 2.x interactive mode

I'm using Python 2.7, and I have the following simple script, which expects one command line argument:

#!/usr/bin/env python

import sys

if (len(sys.argv) == 2):
   print "Thanks for passing ", sys.argv[1]
else:
   print "Oops."

I can do something like this from the command line:

My-Box:~/$ ./useArg.py asdfkjlasdjfdsa
    Thanks for passing  asdfkjlasdjfdsa

or this:

My-Box:~/$ ./useArg.py 
    Oops.

I would like to do something similar from the interactive editor:

>>> import useArg asdfasdf
  File "<stdin>", line 1
    import useArg asdfasdf
                         ^
SyntaxError: invalid syntax

but I don't know how. How can I pass a parameters to import/reload in the interactive editor ?

like image 422
Ampers4nd Avatar asked Sep 17 '13 15:09

Ampers4nd


1 Answers

You can't. Wrap your code inside the function

#!/usr/bin/env python

import sys

def main(args):
    if (len(args) == 2):
        print "Thanks for passing ", args[1]
    else:
        print "Oops."

if __name__ == '__main__':
    main(sys.argv)

If you execute your script from command line you can do it like before, if you want to use it from interpreter:

import useArg
useArg.main(['foo', 'bar'])

In this case you have to use some dummy value at the first position of the list, so most of the time much better solution is to use argparse library. You can also check the number of command line arguments before calling the main function:

import sys

def main(arg):
    print(arg)

if __name__ == '__main__':
    if len(sys.argv) == 2:
        main(sys.argv[1])
    else:
        main('Oops') 

You can find good explanation what is going on when you execute if __name__ == '__main__': here: What does if __name__ == "__main__": do?

like image 125
zero323 Avatar answered Oct 20 '22 03:10

zero323