[英]Fail to pass multiple arguments to a python script in command line
I was trying to write a python script like this: 我正在尝试编写这样的python脚本:
import sys
print sys.argv[1]
print sys.argv[2]
Let's call it arg.py
, and run it in command line: 让我们将其arg.py
,然后在命令行中运行它:
python arg.py one two
it printed: one two. 它打印:一两个。
Everything was fine. 一切都很好。
Then I wanted it to be handy so I put arg.py in my $PATH
and gave it permission to exacuate so wherever I'm I can simply type arg
in command line to run this script. 然后,我希望它可以派上用场,所以我将arg.py放到$PATH
并给予它撤消的权限,因此无论我在哪里,我都可以在命令行中键入arg
来运行此脚本。 I tried 我试过了
arg one two
but it failed. 但是失败了。 The exception said:"bash: test: one: unary operator expected". 异常说:“ bash:测试:one:期望一元运算符”。 But if I just do 但是如果我只是做
arg one
it worked fine. 工作正常。
My question is: why I can't pass multiple arguments like this? 我的问题是:为什么我不能这样传递多个参数? And what is the right way? 正确的方法是什么?
Thanks! 谢谢!
You probably named your script test
, which is a Bash builtin name. 您可能将脚本test
命名为Bash内置名称。 Name it something else. 命名其他。
$ help test
test: test [expr]
Evaluate conditional expression.
Exits with a status of 0 (true) or 1 (false) depending on
the evaluation of EXPR. Expressions may be unary or binary. Unary
expressions are often used to examine the status of a file. There
are string operators and numeric comparison operators as well.
The behavior of test depends on the number of arguments. Read the
bash manual page for the complete specification.
...
That's why you're getting the error from bash
: 这就是为什么您从bash
收到错误的原因:
bash: test: one: unary operator expected
^--------- because it expects an operator to go before 'two'
^-------- and test doesn't like the argument 'one' you've provided
^-------- because it's interpreting your command as the builtin 'test'
^--- Bash is giving you an error
You should parse command line arguments in Python using argparse or the older optparse . 您应该使用argparse或更旧的optparse在Python中解析命令行参数。
Your script, as it is, should work. 您的脚本应该可以正常工作。 Remember to put a shebang line that tells bash to use Python as interpreter, eg #! /usr/bin/env python
切记放一个shebang行,告诉bash使用Python作为解释器,例如#! /usr/bin/env python
#! /usr/bin/env python
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.