简体   繁体   中英

OSError: [Errno 26] Text file busy

Im using python3 and i have this code :

        import tempfile
        temp_file = tempfile.mkstemp(dir="/var/tmp")
        with open (temp_file[1], "w+b") as tf:
            tf.write(result.content)
            tf.close()
        os.chmod(temp_file[1], 0o755)

        if 'args' in command[cmd_type]:
            args = [temp_file[1]] +  command[cmd_type]['args']
        else:
            args = [temp_file[1]]
result = subprocess.run(
    args,
    stdout=subprocess.PIPE,
    universal_newlines=True,
).stdout.strip()

Im creating a tempfile that is a binary file and i get this value from code: /var/tmp/tmp5qbeydbp - that this is the file that has been created and i try to run it in the last subprocess run but i get this error:

client_1  |   File "/usr/local/lib/python3.7/subprocess.py", line 472, in run
client_1  |     with Popen(*popenargs, **kwargs) as process:
client_1  |   File "/usr/local/lib/python3.7/subprocess.py", line 775, in __init__
client_1  |     restore_signals, start_new_session)
client_1  |   File "/usr/local/lib/python3.7/subprocess.py", line 1522, in _execute_child
client_1  |     raise child_exception_type(errno_num, err_msg, err_filename)
client_1  | OSError: [Errno 26] Text file busy: '/var/tmp/tmp5qbeydbp'

Why is file always busy ? it started when i added the chmod command. but without it, it doesnt have permission to run.

Thanks.

mkstemp returns an open file. You need to close it before you can use it. Since the file is open in binary mode anyway, you may as well write directly to the file descriptor.

import tempfile
import os
temp_fd, temp_name = tempfile.mkstemp(dir="/var/tmp")

try:
    os.write(temp_fd, result.content)
    os.close(temp_fd)
    os.chmod(temp_name, 0o755)

    if 'args' in command[cmd_type]:
        args = [temp_name] +  command[cmd_type]['args']
    else:
    args = [temp_file[1]]

    result = subprocess.run(
        args,
        stdout=subprocess.PIPE,
        universal_newlines=True,
    ).stdout.strip()
finally:
    os.remove(temp_name)

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