7

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 ?

Ampers4nd
  • 787
  • 1
  • 11
  • 20

1 Answers1

6

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?

Community
  • 1
  • 1
zero323
  • 322,348
  • 103
  • 959
  • 935
  • 2
    You should also add an example of how to call the script interactively to make your answer complete. – Duncan Sep 17 '13 at 15:11