【问题标题】:Occasional "Permissions Error" returned when running a program that creates many files运行创建许多文件的程序时偶尔返回“权限错误”
【发布时间】:2018-12-06 11:39:42
【问题描述】:

目前我有以下代码:

# 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 保存它的文件?

【问题讨论】:

    标签: python python-3.x permissions subprocess popen


    【解决方案1】:

    您似乎不时尝试在out.txt 被完全删除之前写信给它。你可以做什么:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-18
      • 2021-02-02
      • 1970-01-01
      • 1970-01-01
      • 2017-09-23
      • 1970-01-01
      • 2021-11-02
      • 2012-08-19
      相关资源
      最近更新 更多