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 ?
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With