python - 无法在命令行中将多个参数传递给 python 脚本

标签 python bash

我试图编写一个像这样的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/

相关文章:

python - 值错误 : day is out of range for month

python - 在for循环中获取多个关键字

regex - 使用 sed 将文件中的字符串替换为该名称变量的内容

python - Firefox Webdriver 将插件安装到远程 Webdriver

python - tkinter:在父级中显示的 Toplevel 中的框架

linux - 使用bash脚本进行git克隆,无法读取存储库的密码

ruby - 在 Vagrant 配置 Bash 脚本中运行 Ruby 文件

python - 如何让 `python` 在 WSL bash 中运行 Python 3?

bash - 为什么我不能使用 getopt 在选项和可选参数之间留一个空格?

python - PyQt:QWidget 幻灯片图像未在 QMainWindow 中正确显示