user7096987
user7096987

Reputation: 87

Unable to pass argument from batch file to python file

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.

Upvotes: 0

Views: 1830

Answers (1)

Adriano Martins
Adriano Martins

Reputation: 1808

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')

Upvotes: 4

Related Questions