如何将“打印"输出重定向到文件? [英] How to redirect 'print' output to a file?

查看:78
本文介绍了如何将“打印"输出重定向到文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Python 将打印重定向到 .txt 文件.我有一个 for 循环,当我想将 all 输出重定向到一个文件时,它将 print 输出我的每个 .bam 文件.所以我试着把:

I want to redirect the print to a .txt file using Python. I have a for loop, which will print the output for each of my .bam file while I want to redirect all output to one file. So I tried to put:

f = open('output.txt','w')
sys.stdout = f

在我的脚本的开头.但是我在 .txt 文件中什么也没得到.我的脚本是:

at the beginning of my script. However I get nothing in the .txt file. My script is:

#!/usr/bin/python

import os,sys
import subprocess
import glob
from os import path

f = open('output.txt','w')
sys.stdout = f

path= '/home/xxx/nearline/bamfiles'
bamfiles = glob.glob(path + '/*.bam')

for bamfile in bamfiles:
    filename = bamfile.split('/')[-1]
    print 'Filename:', filename
    samtoolsin = subprocess.Popen(["/share/bin/samtools/samtools","view",bamfile],
                                  stdout=subprocess.PIPE,bufsize=1)
    linelist= samtoolsin.stdout.readlines()
    print 'Readlines finished!'

有什么问题吗?除了这个 sys.stdout 之外还有其他方法吗?

So what's the problem? Any other way besides this sys.stdout?

我需要我的结果如下:

Filename: ERR001268.bam
Readlines finished!
Mean: 233
SD: 10
Interval is: (213, 252)

推荐答案

最明显的方法是打印到文件对象:

The most obvious way to do this would be to print to a file object:

with open('out.txt', 'w') as f:
    print('Filename:', filename, file=f)  # Python 3.x
    print >> f, 'Filename:', filename     # Python 2.x

但是,重定向标准输出也适用于我.对于像这样的一次性脚本来说可能没问题:

However, redirecting stdout also works for me. It is probably fine for a one-off script such as this:

import sys

orig_stdout = sys.stdout
f = open('out.txt', 'w')
sys.stdout = f

for i in range(2):
    print('i = ', i)

sys.stdout = orig_stdout
f.close()

从 Python 3.4 开始,就有一个简单的上下文管理器可用于执行此操作在标准库:

Since Python 3.4 there's a simple context manager available to do this in the standard library:

from contextlib import redirect_stdout

with open('out.txt', 'w') as f:
    with redirect_stdout(f):
        print('data')

从外壳本身外部重定向是另一种选择,通常更可取:

Redirecting externally from the shell itself is another option, and often preferable:

./script.py > out.txt

其他问题:

脚本中的第一个文件名是什么?我没有看到它被初始化.

What is the first filename in your script? I don't see it initialized.

我的第一个猜测是 glob 找不到任何 bamfiles,因此 for 循环不会运行.检查文件夹是否存在,并在脚本中打印出 bamfiles.

My first guess is that glob doesn't find any bamfiles, and therefore the for loop doesn't run. Check that the folder exists, and print out bamfiles in your script.

另外,使用 os.path.join 和 os.path.basename操作路径和文件名.

Also, use os.path.join and os.path.basename to manipulate paths and filenames.

这篇关于如何将“打印"输出重定向到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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