2012-09-18 263 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