I am trying to pass argument from batch file to python as following. It seems nothing has passed to 'sample' variable. My questions are
- How to get argument properly?
- 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:])
Use argparse https://docs.python.org/3/library/argparse.html
Eg: In your python file
Inside your bat file
In your code, you're skipping the first argument twice.
main
gets called withsys.argv[1:]
, skipping the first argument (program name); but thenmain
itself usesargv[1]
... skipping its first argument again.Just pass
sys.argv
untouched tomain
and you'll be fine, for example.Or, perhaps more elegantly, do call
main(sys.argv[1:])
, but then, inmain
, useargv[0]
!