Pass bash argument to python script Pass bash argument to python script bash bash

Pass bash argument to python script


In this case the trick is to pass however many arguments you have, including the case where there are none, and to preserve any grouping that existed on the original command line.

So, you want these three cases to work:

script.sh                       # no argsscript.sh how now               # some numberscript.sh "how now" "brown cow" # args that need to stay quoted

There isn't really a natural way to do this because the shell is a macro language, so they've added some magic syntax that will just DTRT.

#!/bin/shpython script.py "$@"


In the pythonscript script.py use getopt.getopt(args, options[, long_options]) to get the arguments.

Example:

import getopt, sysdef main():    try:        opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])    except getopt.GetoptError as err:        # print help information and exit:        print str(err) # will print something like "option -a not recognized"        usage()        sys.exit(2)    output = None    verbose = False    for o, a in opts:        if o == "-v":            verbose = True        elif o in ("-h", "--help"):            usage()            sys.exit()        elif o in ("-o", "--output"):            output = a        else:            assert False, "unhandled option"    # ...if __name__ == "__main__":    main()


A very goo buit-in parser is argparse. Yo can use it as follows:

  import argparse  parser = argparse.ArgumentParser(description='Process some integers.')  parser.add_argument('integers', metavar='N', type=int, nargs='+',                   help='an integer for the accumulator')  parser.add_argument('--sum', dest='accumulate', action='store_const',                     const=sum, default=max,                   help='sum the integers (default: find the max)')  args = parser.parse_args()  print(args.accumulate(args.integers))