0

I have seen multiple posts on passing the string but not able to find good solution on reading the string passed to python script from batch file. Here is my problem.

I am calling python script from batch file and passing the argument.

string_var = "123_Asdf"

bat 'testscript.py  %string_var%'

I have following in my python code.

import sys

passed_var = sys.argv[1]

When I run the above code I always see below error.

passed_var = sys.argv[1]
IndexError: list index out of range

Has anyone seen this issue before? I am only passing string and expect it to be read as part of the first argument I am passing to the script.

3
  • have you tried passing a string instead of a variable ? perhaps the variable is empty ?
    – user10417531
    Mar 8, 2019 at 12:09
  • also to run a python script you need to prepend the command with python, e.g. python myscript.py your_argument
    – user10417531
    Mar 8, 2019 at 12:13
  • This is how I am exactly calling the code. bat 'D:\\BuildTools\\tools\\python27\\python.exe testscript.py %string_var%
    – siri
    Mar 8, 2019 at 12:19

3 Answers 3

0

Try this:

import sys
for x,parameter in enumerate(sys.argv):
    print(x, parameter)
0
0

If I have read your question and its formatting correctly, I think your .bat file should read:

Set string_var="123_Asdf"
"D:\BuildTools\tools\python27\python.exe" testscript.py %string_var%

Or better still:

Set "string_var=123_Asdf"
"D:\BuildTools\tools\python27\python.exe" testscript.py "%string_var%"

Where %string_var% can be passed with or without its enclosing doublequotes.

0

Your batch file should be a bit simpler, make sure you have your PATH set correctly or else this won't work.

python testscript.py [argument]

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.