将参数从批处理文件传递到 Python
我正在尝试将参数从批处理文件传递到 python,如下所示.似乎没有传递给样本"变量.我的问题是
I am trying to pass argument from batch file to python as following. It seems nothing has passed to 'sample' variable. My questions are
- 如何正确获取参数?
- 当我运行 .bat 来执行这个 python 时如何检查空点错误?执行时我可能无法在 IDE 中看到控制台日志
我的批处理文件 (.bat)
My batch file (.bat)
start python test.py sample.xml
我的python文件(test.py)
My python file (test.py)
def main(argv):
sample = argv[1] #How to get argument here?
tree = ET.parse(sample)
tree.write("output.xml")
if __name__ == '__main__':
main(sys.argv[1:])
在您的代码中,您将跳过第一个参数两次.
In your code, you're skipping the first argument twice.
main
使用 sys.argv[1:]
调用,跳过第一个参数(程序名称);但是main
本身使用argv[1]
...再次跳过它的第一个参数.
main
gets called with sys.argv[1:]
, skipping the first argument (program name); but then main
itself uses argv[1]
... skipping its first argument again.
例如,只需将 sys.argv
原封不动地传递给 main
就可以了.
Just pass sys.argv
untouched to main
and you'll be fine, for example.
或者,也许更优雅一点,调用 main(sys.argv[1:])
,但是在 main
中,使用 argv[0]
!
Or, perhaps more elegantly, do call main(sys.argv[1:])
, but then, in main
, use argv[0]
!