如果脚本没有 运行 正确,似乎无法将错误写入输出文件

Can't seem to write error to output file if a script doesn't run correctly

我编写了一个函数,它读取 运行 一个 python 脚本,然后将它的输出发送到一个文本文件。 如果 运行 的脚本 broken/doesn 不起作用,我试图让它将一个简单的字符串或有问题的错误写入文本文件。 以下是有问题的代码:

                file_dir = a_dir[0]
                file_name = a_dir[1][:-3]
                with open(f'{self.output_directory}\output_{file_name}.txt', 'w') as f:
                    try:
                        subprocess.call(
                            [sys.executable, file_dir], stdout=f)
                    except:
                        f.write("An error occured with the script")

它的第一部分工作正常 - 它 运行 一个功能文件并写入输出。

我需要更具体地说明错误异常吗?任何帮助将不胜感激!

如果您的代码工作正常并且 sys.executable 是 运行 那么也不会有例外,因此您的 f.write 代码不会是 运行。如果您 运行 使用子进程的程序中存在错误,这不会传播到您 运行 它来自的程序中的异常。您必须对这个程序有所了解才能知道存在错误,您可以查看 subprocess.call 函数调用中的 [returncode][1]。另一种选择是,您可以自己加载模块,然后使用 try except 块从其中 运行 代码而不是 运行 新的 python 解释器。如果您不能依赖文件的任何结构,那么您可以将文件作为文本读取,然后 运行 在 try except 结构中使用 eval 或 exec 读取其中的代码,如果您不知道任何有关该文件的事都可能是一个巨大的安全漏洞,让您根本无法执行它,更不用说在您的 运行ning 应用程序的上下文中了。

**late edit read the file as text vice test 这是一个错字 [1]: https://docs.python.org/3/library/subprocess.html#subprocess.Popen.returncode