2

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

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

This also gives me the error 'list index out of range' and th command line looks like this: C:\Users\Administrator\Documents>"C:\Users\Administrator\AppData\Local\Programs\Python\Python36\python.exe" "C:\repo\PythonProgramme.py" 234
1

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%"

1 Comment

@JacquesGaudin You are welcme 😉

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.