2014-02-13 94 views
2

我试图写一个python脚本是这样的:失败多个参数传递给在命令行Python脚本

import sys 

print sys.argv[1] 
print sys.argv[2] 

我们称之为arg.py,并在命令行中运行:

python arg.py one two 

它印:一两。

一切都很好。

然后,我想这是很方便,所以我把arg.py我$PATH并把它允许exacuate所以无论我,我可以简单地在命令行中键入arg运行此脚本。我试过

arg one two 

但它失败了。例外说:“bash:test:one:一元运算符预期”。但如果我只是做

arg one 

它工作正常。

我的问题是:为什么我不能传递这样的多个参数?什么是正确的方式?

谢谢!

+0

您是如何将脚本添加到路径中的? –

回答

4

您可能将您的脚本命名为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 
+0

令人惊叹的答案,谢谢!我不知道“测试”是一个bash内建的。 –

0

你应该使用argparse或旧optparse解析命令行参数在Python。

您的脚本应该可以工作。请记住放置一个shebang行,告诉bash使用Python作为解释器,例如#! /usr/bin/env python

相关问题