Question: Unable to pass argument from batch file to python file


Unable to pass argument from batch file to python file

Answers 1
Added at 2016-12-15 18:12

I am trying to pass an argument from batch file to my python file.
I followed the steps given in these two links:

Here is a part of my python file where I'm trying to pass argument:

def main(argv):
imapServ = ''
filename = 'TestRunLog.log'
attachment = open("{} {}".format(argv[0], filename), 'rb')
....##rest of the code

import sys
if __name__ == '__main__':
   print 'go ahead'
except ImportError:
   print 'hi'

Also, here is the part of batch file which I'm using to send argument to the Python file:

c:\python27\python.exe C:\Users\abcd\Documents\automation\ %%myhome%\Documents\automation\Testresults\%resultDir%

Above, %resultDir% is the variable which is generated based on timestamp.

Here is the output:

go ahead
Traceback (most recent call last):
  File "C:/Users/abcd/Documents/automation/", line 44, in <module>
  File "C:/Users/abcd/Documents/automation/", line 25, in main
    attachment = open("{} {}".format(argv[0], filename), 'rb')
IOError: [Errno 2] No such file or directory: 'C:/Users/abcd/Documents/automation/ TestRunLog.log'

I followed lots of stackoverflow questions regarding this issue but still I'm unable to run. Not sure where the mistake is.

Answers to

Unable to pass argument from batch file to python file

nr: #1 dodano: 2016-12-15 18:12

The issue is related on how python works with argv. In this scenario, when you run:

main(sys.argv[:1]) # (["C:\Users\abcd\Documents\automation\"])

you actually get only the first arguments passed to the python script, which is the current script location.

To get all the arguments but the first, you must fix that array filter:

main(sys.argv[1:]) # ["%%myhome%\Documents\automation\Testresults\%resultDir%"])

Note that the second filter will also include any other arguments that you might add to the command line.

Also, as a side note. You should consider using the STD lib to join the paths. It should be something like this:

from os.path import join
filename = 'TestRunLog.log'
attachment = open(join(argv[0], filename), 'rb')
Source Show
◀ Wstecz