【问题标题】:Python gives "OSError: Text file busy" upon trying to execute temporary filePython 在尝试执行临时文件时给出“OSError:文本文件忙”
【发布时间】:2015-12-09 04:21:32
【问题描述】:

我正在尝试执行以下脚本:

#! /usr/bin/env python3

from subprocess import call
from os import remove
from tempfile import mkstemp

srcFileHandle, srcFileName = mkstemp(suffix = ".c")
binFileHandle, binFileName = mkstemp()
srcFile = open(srcFileHandle, "w")
srcFile.write("""#include <stdio.h>\nint main () { puts("Hello"); }\n""")
srcFile.close()
print("Compiling...")
call(["clang", "-o" + binFileName, srcFileName])
print("Listing...")
call(["ls", "-l", srcFileName, binFileName])
print("Executing...")
call([binFileName])
remove(srcFileName)
remove(binFileName)

但我在输出中收到以下错误:

Compiling...
Listing...
-rwx--x--x 1 samjnaa samjnaa 8650 Dec  9 09:46 /tmp/tmpmx3yy4rm
-rw------- 1 samjnaa samjnaa   50 Dec  9 09:46 /tmp/tmpw27ywvw6.c
Executing...
Traceback (most recent call last):
File "./subprocess_tempfile.py", line 17, in <module>
    call([binFileName])
File "/usr/lib/python3.4/subprocess.py", line 537, in call
    with Popen(*popenargs, **kwargs) as p:
File "/usr/lib/python3.4/subprocess.py", line 859, in __init__
    restore_signals, start_new_session)
File "/usr/lib/python3.4/subprocess.py", line 1457, in _execute_child
    raise child_exception_type(errno_num, err_msg)
OSError: [Errno 26] Text file busy

我应该怎么做才能成功执行程序而不会出现此错误?

请注意,我也为 bin 文件创建了一个单独的临时文件名,因为不能保证与没有扩展名的 srcFileName 相同的名称可用(挑剔,是的,但严格来说我希望是正确的)。

【问题讨论】:

    标签: python subprocess temporary-files


    【解决方案1】:

    您需要在执行前关闭binFileHandle,类似于srcFileHandle 的代码。

    ...
    from os import close, remove  # <---
    ...
    
    print("Executing...")
    close(binFileHandle)  # <---
    call([binFileName])
    ...
    

    【讨论】:

    • 为什么不binFileHandle.close()
    • @BurhanKhalid, binFileHandle 是一个文件描述符。换句话说,它是一个int 对象。
    猜你喜欢
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    • 1970-01-01
    • 2012-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多