0

This is my program(test.py):

#!/usr/bin/python
import sys, getopt
def main(argv):
   inputfile = ''
   outputfile = ''
   try:
      opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
   except getopt.GetoptError:
      print 'test.py -i <inputfile> -o <outputfile>'
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print 'test.py -i <inputfile> -o <outputfile>'
         sys.exit()
      elif opt in ("-i", "--ifile"):
         inputfile = arg
      elif opt in ("-o", "--ofile"):
         outputfile = arg
   print 'Input file is "', inputfile
   print 'Output file is "', outputfile

if __name__ == "__main__":
     main(sys.argv[1:])

Using msdos command line I could pass the -h option(defined in test.py) like this:

python test.py -h         

The msdos command line would then ouput this:

 test.py -i <inputfile> -o <outputfile>

But how would i pass the -h option in python interactive mode as was done using the msdos command line?

0

2 Answers 2

1

May be you could try to hack something with a custom sys.argv but this would be way too hacky, use instead:

>>> from subprocess import call
>>> call(['./test.py', option1, option2, ...])
Sign up to request clarification or add additional context in comments.

Comments

0

The whole idea of the if __name__ == "__main__": line is that this file can be used both as a program and as a module.

So do this:

>>> import test
>>> test.main(['-h'])

If your module wouldn't have the __name__ check you could do just assigning to sys.argv:

>>> import sys
>>> sys.argv = ['-h']
>>> import test

But naturally that would only work the first time the module is loaded. For the next runs you will need to run:

>>> reload(test)

Note: In Python2 reload is a built-in, but in Python3 it is in module imp.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.