简体   繁体   English

读取从批处理文件传递到 python 脚本的字符串参数

[英]Reading string arguments passed from batch file to python script

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.我已经看到多篇关于传递字符串的帖子,但无法找到从批处理文件中读取传递给 python 脚本的字符串的好的解决方案。 Here is my problem.这是我的问题。

I am calling python script from batch file and passing the argument.我正在从批处理文件调用 python 脚本并传递参数。

string_var = "123_Asdf"

bat 'testscript.py  %string_var%'

I have following in my python code.我在我的 python 代码中有以下内容。

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.我只传递字符串并希望它作为我传递给脚本的第一个参数的一部分被读取。

Try this:尝试这个:

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

If I have read your question and its formatting correctly, I think your .bat file should read:如果我已正确阅读您的问题及其格式,我认为您的.bat文件应为:

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.其中%string_var%可以带或不带双引号传递。

你的批处理文件应该更简单一些,确保你的 PATH 设置正确,否则这将不起作用。

python testscript.py [argument]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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