首页 > 解决方案 > OSError: [Errno 26] 文本文件忙

问题描述

我使用python3,我有这个代码:

        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()

我创建了一个临时文件,它是一个二进制文件,我从代码中获取了这个值: /var/tmp/tmp5qbeydbp- 这是已经创建的文件,我尝试在最后一个子进程运行中运行它,但我收到了这个错误:

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'

为什么文件总是忙?当我添加 chmod 命令时它开始了。但没有它,它没有运行权限。

谢谢。

标签: pythonpython-3.x

解决方案


mkstemp返回一个打开的文件。您需要先关闭它,然后才能使用它。由于文件无论如何都是以二进制模式打开的,因此您也可以直接写入文件描述符。

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)

推荐阅读