简体   繁体   中英

How do I pass variable command line arguments for a python script, that runs from a batch file?

I want to start my python script from a batch file. It requires four arguments, that are processed in the script through sys.argv[n]. These arguments are paths, that are varying from programme call to programme call. So how do I create a batch file, where you can transfer new arguments for the programme call everytime you run the code? I have learned Python for just one semester and am stuck with this problem.

Initially I have created a batchfile to test whether the code is even trying to be executed. Of course it ran an error due to the arguments missing. Then I tried to pass the arguments through the batchfile, which didn't work and gave me the error like before 'list index out of range':

set 1= path1
set 2= path2
set 3= path3
set 4= path4
"C:\Users\Administrator\AppData\Local\Programs\Python\Python36\python.exe" "C:\repo\PythonProgramme.py" %1 %2 %3 %4
pause

I expected the code to run, but as already said, the aguments where not being passed. Can somebody help me fix this issue and maybe give me a hint, what to use for varying arguments (paths)?

You need to surround your variable name with % for it to work. You should read the documentation for set and maybe also this article about batch variables.

In the meantime the following should work.

set var1=path1
set var2=path2
set var3=path3
set var4=path4
"C:\[...]\python.exe" "C:\repo\PythonProgramme.py" %var1% %var2% %var3% %var4%
pause

The error you get is from your (unknown) python code.

  • While unusual you can set variable names with just numbers
  • BUT to reference these vars you need to enclose them in percent signs on both sides %1%
  • With %1..%4 you reference the command line args passed to the batch itself,
    if nothing was passed, there are no args for python to process
  • spaces around the equal sign in a set become part of the variable name/content.

While variables names starting with a letter are preferable (as Jacques Gaudin suggests +1), you can try:

"C:\Users\Administrator\AppData\Local\Programs\Python\Python36\python.exe" ^
    "C:\repo\PythonProgramme.py" %1% %2% %3% %4%

or, if the Path'es set may contain spaces:

"C:\Users\Administrator\AppData\Local\Programs\Python\Python36\python.exe" ^
    "C:\repo\PythonProgramme.py" "%1%" "%2%" "%3%" "%4%"

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