Python gives "OSError: Text file busy" upon trying to execute temporary file

Python gives "OSError: Text file busy" upon trying to execute temporary file

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

#! /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 相同的名称可用(挑剔,是的,但我希望严格来说是正确的)。

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

...
from os import close, remove  # <---
...

print("Executing...")
close(binFileHandle)  # <---
call([binFileName])
...