Call python file with optional parameters

535 views Asked by At

I would like to keep the same name of my script, but have one for automatic execution (which would not take any parameters), and one for ad hoc execution (which would take parameters). Would something like the code below work?

#myPythonFile.py
import sys

def main():
  if argv[1] is None:
    #Do something
  elif:
    #Do something else


if __name__ == '__main__':
  main()

Then I could either call

myPythonFile.py

or

myPythonFile.py 'param1', 'param2'

correct?

1

There are 1 answers

0
roymustang86 On

Here is how you can check arguments passed:

#!/usr/bin/python

import sys

print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)

Here is how it would work

~$ ./arg.py 1 2 3
Number of arguments: 4 arguments.
Argument List: ['./arg.py', '1', '2', '3']
~$ ./arg.py  2 3
Number of arguments: 3 arguments.
Argument List: ['./arg.py', '2', '3']

If you use optparse or argeparse however:

def process_arguments():
    """
    Process our command line arguments, the "master" config file,
    and the file holding one or more database connection strings.
    """
    parser = OptionParser()

    parser.add_option('--input', '-i',
                      type='string',
                      dest='input_file',
                      action='store',
                      default='something',
                      help='The input file for method')

    parser.add_option('--output', '-o',
                      type='string',
                      dest='output_file',
                      action='store',
                      default='anythig',
                      help='The output file for method')

    parser.add_option('--debug', '-d',
                      type='string',
                      dest='debug',
                      action='store',
                      default=None,
                      help='Optional debug argument')

    opts, args = parser.parse_args()
    return opts, args
if __name__ == '__main__':
    options, arguments = process_arguments()
    print options, arguments

Here is how it would look

~$ ./opt.py
{'input_file': 'something', 'output_file': 'nothing', 'debug': None}
[]

~$ ./opt.py -i file_name dir_name
{'input_file': 'file_name', 'output_file': 'nothing', 'debug': None}
['dir_name']