我试图编写一个像这样的Python脚本:
import sys
print sys.argv[1]
print sys.argv[2]
我们将其命名为arg.py
,并在命令行中运行它:
python arg.py one two
它打印:一二。
一切都很好。
然后我希望它很方便,所以我将 arg.py 放入我的 $PATH
中,并授予它执行权限,这样无论我在哪里,我都可以简单地输入 arg
在命令行中运行此脚本。我试过了
arg one two
但是失败了。异常表示:“bash:测试:一:预期一元运算符”。但如果我这样做
arg one
效果很好。
我的问题是:为什么我不能像这样传递多个参数?正确的方法是什么?
谢谢!
最佳答案
您可能将脚本命名为 test
,这是 Bash 内置名称。将其命名为其他名称。
$ 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.
...
这就是您从 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
关于python - 无法在命令行中将多个参数传递给 python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21762306/