【问题标题】:How to route the Python script output to a file如何将 Python 脚本输出路由到文件
【发布时间】:2013-05-05 12:32:32
【问题描述】:

我在 python 中有以下脚本。 对于我在范围内(10000): 打印我

上面的一段 python 代码在控制台上打印 i 的值从 0 到 9999。

现在我想将脚本的输出直接路由到外部文件。
在linux上,我可以使用以下命令完成它

$ python python_script.py > python_out.txt

Windows 7、IDLE Python Shell 和 PyLab 下的等效命令是什么?

另外,上面的脚本打印从 0 到 9999 的数字。我想对输出进行快照, 即我想将前 85 条记录/号码路由到 out1.txt 或 我想将可被 5 整除的数字路由到 out2.txt 无需更改实际脚本。

还请提供 Python 文档以了解更多信息。

【问题讨论】:

  • cygwin 有帮助吗?
  • 不改变实际脚本是什么意思?如果您想根据某些条件写入不同的文件,那么您必须修改脚本。

标签: python file output routes


【解决方案1】:
file1, file2 = "out1.txt", "out2.txt"
with open(file1,'w') as f1,open(file2,"w") as f2:
    for i in range(10000):
        if i < 85:
            f1.write("{0}\n".format(i))  # write to out1.txt
        if i%5==0:
            f2.write("{0}\n".format(i))  #write to out2.txt
        print i                 #write to stdout or python_out.txt in your case

然后运行这个程序:

$python python_script.py > python_out.txt

【讨论】:

  • 嗨 Ashwini,我不想更改 Python 脚本。 Python脚本很好。您的 python 代码仅适用于命令行。它无法通过直接调用 python 脚本正常运行,因为它需要 2 个文件名作为 args。这不是我所期望的。更多的命令在 Windowsn 上不起作用
  • @Kranti 这些命令在 windows、linux 或 mac 中运行良好,我已经更改了代码,您只需在代码中指定文件名即可。您如何期望脚本在不更改脚本的情况下以不同的方式运行?
  • Ashwini,我尝试了很多方法来运行命令,但没有运气。我已经在 facebook 上添加了你。你能上网帮帮我吗?
  • @Kranti 哪个命令? python_script.py &gt; python_out.txt 只会写信给python_out.txt。你不能指望像for i in range(10000): print i 这样的脚本会以某种方式神奇地将输出写入3 个不同的文件,这也是有条件的。抱歉,没有关于 fb 或邮件的问题。
  • 是的,我打开 cmd 提示符并进入 Python shell。在获取 >>> 我输入了命令 C:\Users\Kranti\Desktop\Python\python_script.py 我收到了语法错误。
【解决方案2】:

代码有点难看,但您不必更改脚本。

class A:
    def __init__(self, filename, predicate=(lambda ln, v:True)):
        self.filename = filename
        self.lines = 0
    def write(self, text):
        if predicate(self.lines, text):
            with open(self.filename, 'a') as f:
                f.write(text)
        self.lines += text.count('\n')

用法:

import sys

def predicate(linenumber, text):
    if text.isdigit():
        if int(text) % 5:
            return False
    return True

sys.stdout = A('out1.txt', predicate)

for i in range(10000):
    print i

【讨论】:

    【解决方案3】:

    您必须打开一个文件并在其中写入,就像这样。

    f = open('write_to_this_file.txt', 'w')
    for i in xrange(10000):
        f.write(i + "\n")
    

    这里有更多信息http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files

    【讨论】:

    • 不,这是直截了当的答案。但我想知道使用 python 命令将程序输出路由到文件的替代方法
    猜你喜欢
    • 1970-01-01
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    相关资源
    最近更新 更多