简体   繁体   中英

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

I'm trying to execute the following script:

#! /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)

But I'm getting the following error in output:

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

What should I do to be able to successfully execute the program without getting this error?

Note that I'm creating a separate temporary file name for the bin file too since there is no guarantee that the same name as srcFileName without the extension is available (picky, yes, but strictly speaking correct I hope).

You need to close the binFileHandle before execution, similarily the code did for srcFileHandle .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM