2011-02-18 77 views
0

我有以下代碼是從一個問題的工作分開。我試圖比較來自commands.getoutput(cmd)的兩個輸出,但即時獲取語法錯誤。據我所知,這可能是天生錯的,但也有人指出在做什麼我錯了比較輸出

def DiffGenerator(): 

    try: sys.argv[1] 
    except: print "No Directory to scan defined\n" 

    try: sys.argv[2] 
    except: print "No delay time defined\n" 

    ScanDirectory = sys.argv[1] 
    if not os.path.exists(ScanDirectory): 
    print "Scan Directory does not exist :" + ScanDirectory 

    cmd = "ls -l " + ScanDirectory 

    try: 
    DiffFileA = commands.getoutput(cmd) 
    print "Printing DiffFileA" + DiffFileA 
    time.sleep(1) 
    DiffFileB = commands.getoutput(cmd) 
    if operator.ne(DiffFileA, DiffFileB) 
     print "New File placed within " + ScanDirectory 
    except: 
    print "BLAH" 

回答

0

你可能要考慮子

http://docs.python.org/library/subprocess.html

subprocess.Popen(['ls','-a'], stdout = subprocess.PIPE, stdin = subprocess.PIPE) 
results = subprocess.communicate()[0] #where [0] is the stdout and [1] is the stderr 

編輯:

也可以你可以擴大你的嘗試除了循環,並使用特定的例外,例如

壞:

try: sys.argv[1] 
except: print "No Directory to scan defined\n" 

好:

try: 
    sys.argv[1] 
except IndexError: 
    print "No directory to scan defined\n" 
0

if operator.ne(DiffFileA, DiffFileB)缺少一個冒號,這可以解釋一個SyntaxError。順便說一句,報告錯誤時,請複製並粘貼正是您看到的錯誤消息。

但如果使用operator.ne(A,B):是寫一個非常unpythonic方式,如果A = B:和我儘量吧!

+0

我是新來編寫Python這樣的IM確保ü可以理解爲什麼我會遇到這樣的事情。什麼是更好的方式去A!= B – paultop6 2011-02-18 11:27:12