Passing Argument from Batch File to Python

2019-08-20 07:38发布

问题:

I am trying to pass argument from batch file to python as following. It seems nothing has passed to 'sample' variable. My questions are

  1. How to get argument properly?
  2. How to check null point error when I am running .bat to execute this python? I may not be able to see the console log in IDE while executing

My batch file (.bat)

start python test.py sample.xml

My python file (test.py)

def main(argv):
    sample = argv[1]   #How to get argument here?
    tree = ET.parse(sample)
    tree.write("output.xml")

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

回答1:

In your code, you're skipping the first argument twice.

main gets called with sys.argv[1:], skipping the first argument (program name); but then main itself uses argv[1]... skipping its first argument again.

Just pass sys.argv untouched to main and you'll be fine, for example.

Or, perhaps more elegantly, do call main(sys.argv[1:]), but then, in main, use argv[0]!



回答2:

Use argparse https://docs.python.org/3/library/argparse.html

Eg: In your python file

import argparse

parser = argparse.ArgumentParser(description='Your prog description.')
parser.add_argument('-f','--foo', help='Description for foo argument', required=True)
    :
    :
args = parser.parse_args()

Inside your bat file

python prog.py -f <foo arg here>