Python 2.7:调用subprocess.popen阻止文件访问



我正在尝试开发一个简单的函数

  • 打开一个文件,
  • 启动一个子进程,
  • 然后关闭文件,
  • 然后将文件移动到其他位置,然后
  • 然后停止子进程。

发生的情况是,只要子进程仍在执行,我就无法移动文件,即使我看不到两者是如何连接的。由于这个问题,我移动了代码部分以将文件移动到一个线程中,该线程一遍又一遍地重试,并且只有在子进程终止后它才会最终成功(我知道终止可以更优雅地完成,但这不是我关心的问题(。我需要做些什么来使文件在子进程仍在运行时可访问,以便我可以避免将其转移到后台进程(我宁愿在我实例化线程的地方调用 os.rename?使用 Python 2.7

import sys
import threading
import time
import random
import subprocess
import os
def GetFN():
return 'C:\temp\' + str(random.randint(0,1000000)) + '.AVI'
class MoveFileThread(threading.Thread):
def __init__(self, FromFilePath, ToFilePath):
super(MoveFileThread, self).__init__()
self.FromFilePath = FromFilePath
self.ToFilePath = ToFilePath
def run(self):
while True:
try:
os.rename(self.FromFilePath, self.ToFilePath)
print "Moved file to final location: " + self.ToFilePath
break
except Exception as err:
print str(self.FromFilePath) + "'. Error: " + str(err)
time.sleep(1)
if __name__ == "__main__":
filename = GetFN()
out = open(os.path.normpath(filename), "a")
process = subprocess.Popen(['ping', '-t', '127.0.0.1'], stdout=subprocess.PIPE)
time.sleep(2)
out.close()
MoveFileThread(filename, GetFN()).start()
time.sleep(5)
subprocess.Popen("TASKKILL /F /PID {pid} /T".format(pid=process.pid))
time.sleep(3)

执行时的代码将产生以下输出:

C:temp771251.AVI'. Error: [Error 32] The process cannot access the file because it is being used by another process
C:temp771251.AVI'. Error: [Error 32] The process cannot access the file because it is being used by another process
C:temp771251.AVI'. Error: [Error 32] The process cannot access the file because it is being used by another process
C:temp771251.AVI'. Error: [Error 32] The process cannot access the file because it is being used by another process
C:temp771251.AVI'. Error: [Error 32] The process cannot access the file because it is being used by another process
C:temp771251.AVI'. Error: [Error 32] The process cannot access the file because it is being used by another process
Moved file to final location: C:temp560980.AVI

这里的答案是子进程启动的新线程从主线程继承所有打开的文件句柄。这可以通过在前面的 open 语句中添加"N"标志来避免。

out = open(os.path.normpath(filename), "a")

有关更多详细信息,请参阅如何:close_fds=True 的解决方法和重定向 stdout/stderr

相关内容

  • 没有找到相关文章

最新更新