简体   繁体   中英

python os.system seems to hang for no reason

So I am monitoring the modification time of numerous files. When the file is updated, I copy it over ssh to another machine. Here is a SSCCE of what I have:

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

So when it gets to the os.system() command it hangs there not doing anything... however when I run the same exact code on the python interpreter it works just fine. I can't seem to understand what the issue would be... any help would be great!

The sudo is the likely culprit and is probably asking for a password.

Instead of os.system , try using the subprocess module instead. That will let you see the stdout and stderr streams to see what is going on.

Also, I would question the practice of using sudo inside your script. Normally, the decision to use sudo would be left to the person calling the Python script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM