2013-04-21 71 views
1

所以我正在監視衆多文件的修改時間。當文件更新時,我通過ssh將它複製到另一臺機器上。這裏是什麼,我有一個SSCCE:python os.system似乎無端掛起

import os 
import time 

send = "/home/pi/PythonScripts/tempData.txt" 
check = "/home/pi/PythonScripts/check.txt" 

statbuf = os.stat(send) 
print "Modification time:",statbuf.st_mtime 

def wr2(data): 
    file2 = open(check, 'w') 
    file2.write(str(data)) 
    file2.close() 
    return 0 

def rd(): 
    file = open(send, 'r') 
    line2 = file.readline() 
    file.close() 
    return line2 

def rd2(): 
    file2 = open(check, 'r') 
    line2 = file2.readline() 
    file2.close() 
    return line2 


while(run): 
    try: 
    statbuf = os.stat(send) 
    line2 = rd2() 
    print line2 

    if (str(statbuf.st_mtime) == line2): 
     print "File has not changed...\n" 
     time.sleep(1) 
    else: 
     data = rd() 
     print "Data in File: " + data 
     os.system("sudo scp /home/pix/PythonScripts/tempData.txt server1:/home/tix/Server1_SSH/Real_Data.txt") 
     wr2(statbuf.st_mtime) 
     print "New Modification Time:",statbuf.st_mtime 
     time.sleep(1) 



    except (KeyboardInterrupt, SystemExit): 
     print '\nKeyboard Interrupt Caught!' 
     run = 0 
     raise 

所以當它到達os.system()命令它掛在那兒沒有做任何事情......但是當我在Python解釋器運行完全相同的代碼,它工作得很好。我似乎無法理解這個問題會是什麼......任何幫助都會很棒!

回答

2

sudo是可能的罪魁禍首,並可能要求輸入密碼。

而不是os.system,請嘗試使用subprocess module來代替。這將讓你看到標準輸出stderr流,看看發生了什麼。

此外,我會質疑在腳本中使用sudo的做法。通常,決定使用sudo將留給調用Python腳本的人。

+0

我也這麼認爲,但是在python解釋器中,它工作得很好,沒有任何問題... – skbeez 2013-04-21 00:49:23

+1

其實你是對的,我刪除了sudo,現在它完美地工作。謝謝! – skbeez 2013-04-21 01:59:23