将参数从批处理文件传递到 Python [英] Passing Argument from Batch File to Python

查看:57
本文介绍了将参数从批处理文件传递到 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

  1. 如何正确获取参数?
  2. 当我运行 .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]!

这篇关于将参数从批处理文件传递到 Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆