简体   繁体   中英

Passing arguments to python script from batch file

I want to pass arguments from test.bat to myscript.py .

test.bat :

../path/to/file/myscript.py "myarg1" "myarg2"

myscript.py :

#!/usr/bin/env python2

import sys

if __name__ == '__main__':

    print sys.version()
    myarg1= sys.argv[1]
    myarg2= sys.argv[2]

I am using windows 10 and configured pylauncher as default program to execute python files. I have both python 2.7 and 3.6 in my user and system PATH variables. The shebang is taken care and py2.7 interpreter is chosen as expected.

Error I am facing is that the arguments are not passed. Error log reads as below:

2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:22:17) [MSC v.1500 32 bit (Intel)]
Traceback (most recent call last):
File "C:\full\path\to\file\myscript.py", line 12, in <module>
myarg1= sys.argv[1]
IndexError: list index out of range

One solution: When I specify py in my .bat file it works and arguments are read correctly

py ../path/to/file/myscript.py "myarg1" "myarg2"

How can I make this work without adding py to my .bat script?

More info - running these in cmd shell:

assoc .py gives .py=Python.File

ftype Python.File gives Python.File="C:\\WINDOWS\\py.exe" "%L" %*

You WILL have to have .py on the end of the filename in order for this to work. Your test.bat file should look like this:

python myscript.py [arg1] [arg2]

If the myscript.py file is not in the same directory then put the path to myscript.py ENDING IN myscript.py.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM