2013-12-16 62 views
0

時運行下面的腳本時,我收到以下錯誤,可以anyhelp以確定是什麼問題,以及如何克服它類型錯誤運行命令

CODE: -

import sys 
import os 

def main(): 
    to = '' 
    with open('caf_gerrits.txt','r') as f : 
     for gerrit in f : 
      print "Gerrit " + gerrit 
      cmd = "ssh -p 29418 review-android.company.com gerrit query --format=JSON --current-patch-set --commit-message --files \'%s\' >> gerrit_output.txt" %(gerrit) 
      os.system(cmd) 


if __name__ == '__main__': 
    main() 

錯誤: -

Gerrit 530731 

Traceback (most recent call last): 
    File "test.py", line 14, in <module> 
    cmd = "ssh -p 29418 review-android.company.com gerrit query --format=JSON --current-patch-set --commit-message --files \'%s\' >> gerrit_output.txt" %(gerrit) 
    File "test.py", line 10, in main 
    to = '' 
TypeError: must be string without null bytes, not str 
+0

您使用的是什麼版本的Python?我沒有得到CPython 2.7,Pypy 2.2或Jython 2.7b1的這個錯誤。 – dstromberg

+0

我複製/粘貼並更改cmd,腳本工作。所以可能是你有些事情沒有在這裏顯示導致問題。從錯誤消息中,第10行是='',但我們沒有在你的源代碼中看到它。我們在這裏錯過了一些東西嗎? – PasteBT

+0

@PasteBT - 我正在使用pythong 2.7.3,你是否創建了一個文件caf_gerrits並擁有一些像530731那樣的digist? – user2955256

回答

-1

嘗試使用:

for gerrit in f.readlines(): 

您正在嘗試使用文件描述符進行迭代,而不是文件本身的內容。

+0

你正在使用哪個版本的python? – PasteBT

+0

@PasteBT - 正在使用python 2.7.3 – user2955256

+0

@MattDmo - 你的建議沒有幫助 – user2955256

0

問題是在我打賭的文件之後逃脫的單引號。由於您在外部使用雙引號,因此無需轉義它們。

使用'subprocess'模塊的替代解決方案如下所示。注意這只是在這裏輸入,我沒有運行它。它應該接近。

def main(): 
    to = '' 
    ssh_command = ["ssh", "-p", 29418, "review-android.company.com", "gerrit", 
        "query", "--format", "JSON", "--current-patch-set", 
        "--commit-message", "--files", ] 

    with open('gerrit_output.txt', 'a') as fp: 
     with open('caf_gerrits.txt','r') as f : 
      for gerrit in f : 
       print "Gerrit " + gerrit 
       result = subprocess.check_output(ssh_command + [gerrit, ]) 
       fp.write(result) 

if __name__ == '__main__': 
    main() 

查看'subprocess'模塊的文檔,還有很多其他的方法來完成這個。任何你選擇的方式你都可以得到更好的錯誤處理和更好的輸出捕捉,而不僅僅是一個簡單的'os.system'調用。

+0

順便說一句,檢查'subprocess'模塊。它比單純使用'os.system'具有更好的功能。 –

+0

你能建議誰來使用子進程而不是os.system嗎? – user2955256