1

**Updated because of comments

I am trying to pass a variable from a batch file to my python files. I am getting a n unexpected result; my code:

In my batch file:

SET variablename = 'name'
python 01_preparing.py %variablename%

In my python file

import sys

print('Argument:', sys.argv[1])

Result is

Traceback (most recent call last):
File "01_preparing.py", line 5, in <module>
print('Argument:', sys.argv[1])
IndexError: list index out of range

Started out with this example: Sending arguments from Batch file to Python script

Zuenie
  • 963
  • 2
  • 11
  • 30
  • 1
    you want another `%` sign, i.e. `python 01_preparing.py %variablename%` might work. (I'm typing this from a linux box and my memory is ~10 years old) – Sam Mason Oct 16 '18 at 19:26
  • 4
    1) you use a variable with `%variablename%`. 2) remove any spaces around `=` - they become part of the variable name / it's value. – Stephan Oct 16 '18 at 19:26
  • it doesnt seem to work; I am probably implementing it wrong, ill update the question – Zuenie Oct 16 '18 at 19:29
  • ok. So I should use os in stead of sys – Zuenie Oct 16 '18 at 19:35
  • Both are possible. But in this case `os.environ` should work fine, since the python process can access environment variables from the parent process. (`SET` creates an environment variable) – Håken Lid Oct 16 '18 at 19:37
  • Ok so my mistake was that it should be: SET variablename= 'name'. Without a space between variablename and =. It somehow took a space with it in the background. Works now :) thanks! – Zuenie Oct 16 '18 at 19:45
  • 2
    @Zuenie, that is what Stephan was pointing out with his 2nd bullet point. But if you would open up a command prompt and type: `set /?`, you could read the help file, which shows the correct syntax. `SET [variable=[string]]`. No spaces in that syntax. – Squashman Oct 16 '18 at 20:00

0 Answers0