2011-01-23 63 views
0

我沒弄清楚如何使用Python中的lib提供的Cmd的模塊,但我現在有麻煩......Python交互Cmd的問題(3個參數的問題)

下面是代碼:

def do_addtext(self, file, text = ""): 
     "Add text to the end of a file" 
     if os.path.exists(file) == True: 
      f = open(file, 'a') 
      f.write("\n" + text) 
      print "\n>>> Text added!\n" 
     else: 
      print "\n>>> File do not exists\n" 

當我使用只有兩個參數的函數時,它工作的很好,但我不能用三個參數來使用它。

所以這是很好調用一個函數,如「創建file.txt的」,但我不能用這個......「addtext file.txt的SomeText」則會

我想在命令行上不承認有是三個不同的領域?

對此有何幫助?

謝謝。

+0

謝謝。我更改名稱文件並刪除了== True。我通過命令行工作仍然存在問題..它不能識別第三個參數。 – PGZ 2011-01-23 19:32:10

+0

你是怎麼調用這段代碼的? – user225312 2011-01-23 19:33:07

回答

4

當Cmd對象解析輸入時,它取第一個單詞並將其用作函數名稱。文本的其餘部分作爲單個參數傳入。 do_ *函數只需要2個參數:self和來自輸入的字符串的其餘部分。所以,如果你鍵入:

> foo This is my text 

在提示符下,然後CMD將嘗試調用一個函數self.do_foo(「這是我的文本」)。它不會將字符串拆分爲分隔符參數。也就是說,它不會嘗試調用self.do_foo(「This」,「is」,「my」,「text」)。

如果你想讓你的函數處理更多的參數,你需要自己分析一下這一行。現在,你有3個參數do_addtext。所以,你將不得不重新編寫do_addtext到只有2個參數,是這樣的:

do_addtext(self, parameter): 
    "Add text to end of file." 
    filename,text = parameter.split(" ", 1) # <--- this does the parsing you wanted Cmd to do 
    if os.path.exists(filename) == True: 
    f = open(filename, 'a') 
    f.write("\n" + text) 
    print "\n>>> Text added!\n" 
    else: 
    print "\n>>> File do not exists\n" 

而且,看到這個wiki on CmdModule。它有對do_xxx方法的解釋。