简体   繁体   English

使用 sys.argv 将命令行 arguments 传递给 python 脚本

[英]Using sys.argv to pass command line arguments to a python script

I know this question has been asked in various variations but none of them seem to work for my specific case:我知道这个问题已经以各种不同的方式提出,但它们似乎都不适用于我的具体情况:

(btw all mentioned files are in my PATH) (顺便说一句,所有提到的文件都在我的路径中)

I have a simple python script called test.py:我有一个名为 test.py 的简单 python 脚本:

import sys

print('Hello world!')
print(sys.argv)

counter = 0

while True:
    counter +=1

The counter is just there to keep the command window open so don't worry about that.计数器只是在那里保持命令 window 打开所以不用担心。

When I enter当我进入

test.py test test 

into cmd I get the following output:进入 cmd 我得到以下 output:

Hello world!
['C:\\Users\\path\\to\\test.py']

For some reason unknown to me the two other commands (sys.argv[1] and sys.argv[2]) are missing.由于某些我不知道的原因,缺少其他两个命令(sys.argv[1] 和 sys.argv[2])。

However when I create a.bat file like this:但是,当我像这样创建一个 .bat 文件时:

@C:\Users\path\to\python.exe C:\Users\path\to\test.py %*

and call it in cmd并在 cmd 中调用它

test.bat test test

I get my desired output:我得到了我想要的 output:

Hello world!
['C:\\Users\\path\\to\\test.py', 'test', 'test']

I've read that the我读过

%* %*

in the.bat file means that all command line arguments are passed to the python script but why are exactly these arguments not passed to the python script when I explicitly call it in cmd? in the.bat file means that all command line arguments are passed to the python script but why are exactly these arguments not passed to the python script when I explicitly call it in cmd?

From what I've read all command line arguments entered after the script name should be passed to said script but for some reason it doesn't work that way.从我读过的所有命令行 arguments 在脚本名称应该传递给所述脚本之后输入,但由于某种原因它不能那样工作。

What am I overlooking here?我在这里俯瞰什么?

I'm guessing that you need to actually run the script through the command line with C:\Users\path\to\python.exe test.py test test .我猜你需要通过命令行实际运行脚本C:\Users\path\to\python.exe test.py test test

I'm not sure how Windows handles just test.py test test but from my limited experience it is probably just trying to open all 3 of those files.我不确定 Windows 如何处理test.py test test ,但根据我有限的经验,它可能只是试图打开所有 3 个文件。 Since the first one ( test.py ) has a .py extension, it is opened with the Python Interpreter and is run automatically.由于第一个( test.py )具有.py扩展名,因此它使用 Python 解释器打开并自动运行。 The other two are not actually being passed in as an argument.另外两个实际上并没有作为参数传入。

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

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