我使用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()
我正在创建一个tempfile,它是一个二进制文件,我从代码中得到这个值:/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)