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

Question

Unable to pass argument from batch file to python file

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

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 = 'imap.gmail.com'
filename = 'TestRunLog.log'
attachment = open("{} {}".format(argv[0], filename), 'rb')
....##rest of the code

import sys
try:
if __name__ == '__main__':
   print 'go ahead'
   main(sys.argv[:1])
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\testsendemail.py %%myhome%\Documents\automation\Testresults\%resultDir%
pause

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

Here is the output:

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

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