python - 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 命令时它开始了。但没有它,它没有运行权限。
谢谢。
解决方案
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)
推荐阅读
- git - 操作系统恢复后如何恢复 Git 存储库
- android - Android LiveData 观察者未触发
- node.js - Hooks 只能在函数组件内部调用
- python - Flask 应用程序与动态列表和元组的行为不符
- spring-boot - 如何在接口投影中为以 is 开头的布尔变量正确设置 getter setter?
- python - 加入两个有条件的数据框
- wpf - Xamarin.Forms for WPF TapGestureRecognizer 双击不触发 ListView
- php - 计算 foreach 中的循环并以此为基础采取行动
- excel - 遍历列
- c# - 将 Json 键值对解析为 POCO 属性