2012-09-18 189 views
0

您好我是新来的Python和当前已复制下面的脚本:的命令行参数传递蟒蛇

# filename is printer.py 
import sys 
for arg in sys.argv: 
    print arg # the zeroth element is the module name 
raw_input("press any key") # a trick to keep the python console open 

我想获得的参数,然后模块名称。 但运行此代码给我下面的错误:

U:\printer.py 
    File "U:\printer.py", line 6 
     print arg # zeroth element is the module name 
      ^
SyntaxError: Invalid syntax 

有谁知道什么可能是错在这里? 我使用Python 3.2

回答

5

在Python 3 print是一个函数:

print(arg) 
2

Python 3里不再有print关键字,但print功能。

尝试,而不是

print(arg) 
5

正如其他人所指出的,在python3,print是一个函数:

print arg 

现在:

print(arg) 

此外,raw_input不见了,取而代之通过简单的input。 (在py2k中,inputeval命令行中的字符串,但它不会在py3k中这样做)。


最后(也可能是最重要的),你有没有考虑​​? (未经测试的代码如下

import argparse 
parser = argparse.ArgumentParser() 
parser.add_argument('foo',nargs='*',help="What a nice day we're having") 
args = parser.parse_args() 
print(args.foo) 
+0

此外, “按任意键” 是骗人的,不管你是使用'raw_input'或'input'。 – geoffspear

+0

@Woobie - 好点。它应该是“按回车”。 – mgilson