我有一个非常简单的用例,我必须在 2 个不同的目录中找出过去 10 分钟内修改过的文件。
由于有两个不同的目录,因此我启动了两个单独的线程来执行此操作,并且在每个正在运行的线程中,存在检查已修改文件的逻辑。
以下是相同的代码:
import threading
import os
import time
from subprocess import Popen, PIPE
def getLatestModifiedFiles(seconds, _dir):
files = (fle for rt, _, f in os.walk(_dir) for fle in f if time.time() - os.stat(
os.path.join(rt, fle)).st_mtime < 300)
return list(files)
def getLatestModifiedFilesUnix(seconds, _dir):
lastseconds = seconds * -1
p = Popen(['/usr/bin/find', _dir, '-mmin', str(lastseconds)], stdout=PIPE, stderr=PIPE)
out, err = p.communicate()
print out.strip("\r\n")
if err != "":
print err
def run(logPath):
threadName = threading.currentThread().getName()
getLatestModifiedFilesUnix(10, logPath)
#files = getLatestModifiedFiles(300,logPath)
#for file in files:
# print "message from %(ThreadName)s...%(File)s" % {'ThreadName': threadName, 'File' : file}
if __name__ == "__main__":
logPaths = ["/home/appmyser/Rough", "/home/appmyser/Rough2"]
threads = []
for path in logPaths:
t = Thread(target=run, args=(path,))
threads.append(t)
t.start()
for t in threads:
t.join()
函数:getLatestModifiedFiles
使用本机 Python 代码查找最新修改的文件,另一方面,函数:getLatestModifiedFilesUnix
使用 unix find 命令执行相同的操作。
在第二种情况下,我使用子进程,据我所知,它创建了一个新进程。我的问题是,从线程中调用子进程是一种好习惯吗?有什么我应该考虑的后果吗?
另外新创建的子进程的父进程是什么?有人可以详细地向我指出它是如何工作的吗?
提前谢谢了。