如何执行python脚本并将输出写入txt文件? [英] How to execute a python script and write output to txt file?

查看:1143
本文介绍了如何执行python脚本并将输出写入txt文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在执行一个.py文件,该文件吐出了一个给定字符串.该命令正常工作

I'm executing a .py file, which spits out a give string. This command works fine

execfile('file.py')

execfile ('file.py')

但是我希望将输出(除了在外壳中显示)写入文本文件.

But I want the output (in addition to it being shown in the shell) written into a text file.

我尝试了这个,但是不起作用:(

I tried this, but it's not working :(

execfile('file.py')>('output.txt')

execfile ('file.py') > ('output.txt')

我所得到的就是这个

tugsjs6555

tugsjs6555

错误

我猜"False"是指输出文件未成功写入:(

I guess "False" is referring to the output file not being successfully written :(

感谢您的帮助

推荐答案

您正在做的是对照字符串'output.txt'

what your doing is checking the output of execfile('file.py') against the string 'output.txt'

您可以使用子流程来完成您想做的事情

you can do what you want to do with subprocess

#!/usr/bin/env python
import subprocess
with open("output.txt", "w+") as output:
    subprocess.call(["python", "./script.py"], stdout=output);

这篇关于如何执行python脚本并将输出写入txt文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆