运行创建许多文件的程序时偶尔返回"Permissions Error"



目前我有以下代码:

# Open a place holding output file
with open('out.txt', 'w') as f:
# Run BOLSIG-
r = Popen("%s %s" % (bolsig, infile), stdout=f, cwd=outputdir)
# Wait for BOLSIG- to complete
Popen.wait(r)
# Remove the created output file as it is not used and BOLSIG- creates it's own file
remove('out.txt')

它获取一个.exe文件(bolsig(并运行其程序,并向正在运行的程序输入一个文件名(infile(,然后程序打开并相应地执行该文件,输出其自己的文件。此脚本通常使用多达1000个输入文件运行。

我能让Popen允许bolsig保存其输出文件的唯一方法是创建一个"保留"文件out.txt,然后删除它。通常情况下,这很好,但偶尔程序会输出80/90/100个文件,然后突然出现一行

with open('out.txt', 'w') as f:

将抛出以下错误,

Traceback (most recent call last):
File "C:/Users/minec/Desktop/College/4th_Year/Final Year Project/Program/Master-Program.py", line 1129, in <module>
main()
File "C:/Users/minec/Desktop/College/4th_Year/Final Year Project/Program/Master-Program.py", line 45, in main
outputdir = bolsig_minus(runfilelist)
File "C:/Users/minec/Desktop/College/4th_Year/Final Year Project/Program/Master-Program.py", line 496, in bolsig_minus
with open('out.txt', 'w') as f:
PermissionError: [Errno 13] Permission denied: 'out.txt'

有人知道为什么它只是偶尔抛出这个错误吗?如果是这样的话,我该如何修复它或修改代码,使其完全不使用out.txt文件,但仍然允许Popen保存它的文件?

似乎不时会尝试在out.txt被完全删除之前对其进行写入。你能做什么:

  1. 在开始新脚本之前添加一些time.sleep()
  2. 在运行Popen之前,检查out.txt是否不存在
  3. 使用此库处理临时文件:https://docs.python.org/2/library/tempfile.html

我认为最好的方法是将数字3与数字2相结合。

最新更新