Python写入临时文件后作为子进程执行遇Text file busy错误的问询
问题原因与解决办法
核心原因
你忽略了一个关键细节:tempfile.NamedTemporaryFile(delete=False)返回的script本身就是一个处于打开状态的文件对象。哪怕你自己额外打开一个文件句柄并关闭,这个初始的句柄依然没关。Linux系统禁止执行带有未关闭写句柄的可执行文件,这就是触发Text file busy错误的根本原因。
修复方案
只需要在写入内容后,先关闭script这个初始文件对象,再执行后续的加权限和子进程调用操作即可。
方案1:直接用初始对象写入(更简洁)
def chmod_plus_x(file_path: str) -> None: st = os.stat(file_path) os.chmod(file_path, st.st_mode | stat.S_IEXEC) try: # 指定文本模式,避免字节串写入的麻烦 script = tempfile.NamedTemporaryFile(delete=False, mode='w') script.write("ls /") script.flush() script.close() # 关键:关闭初始文件句柄 chmod_plus_x(script.name) subprocess.run(script.name, shell=False) finally: os.remove(script.name)
方案2:先关闭初始句柄再重新写入
def chmod_plus_x(file_path: str) -> None: st = os.stat(file_path) os.chmod(file_path, st.st_mode | stat.S_IEXEC) try: script = tempfile.NamedTemporaryFile(delete=False) script.close() # 先关闭初始句柄 f = open(script.name, "w") f.write("ls /") f.flush() f.close() chmod_plus_x(script.name) subprocess.run(script.name, shell=False) finally: os.remove(script.name)
方案3:用with语句自动管理句柄
def chmod_plus_x(file_path: str) -> None: st = os.stat(file_path) os.chmod(file_path, st.st_mode | stat.S_IEXEC) try: with tempfile.NamedTemporaryFile(delete=False, mode='w') as script: script.write("ls /") # with块结束后,script会自动关闭 chmod_plus_x(script.name) subprocess.run(script.name, shell=False) finally: os.remove(script.name)
内容的提问来源于stack exchange,提问作者Alira
相关产品推荐
相关产品推荐

