重定向API Stderr python

时间:2014-09-01 11:56:53

标签: python stderr

我正在使用python包https://pypi.python.org/pypi/mygene 做一些基因id映射。我的代码如下:

#! /usr/bin/env python

# ID mapping using mygene
# https://pypi.python.org/pypi/mygene
# http://nbviewer.ipython.org/gist/newgene/6771106
# http://mygene-py.readthedocs.org/en/latest/
# 08/30/14

__author__ = 'tommy'

import mygene
import fileinput
import sys


mg = mygene.MyGeneInfo()

# mapping gene symbols to Entrez gene ids and Ensemble gene ids.
# fileinput will loop through all the lines in the input specified as file names given in command-line arguments,
# or the standard input if no arguments are provided.

# build a list from an input file with one gene name in each line
def get_gene_symbols():
    gene_symbols = []
    for line in fileinput.input():
        gene_symbol = line.strip()  # assume each line contains only one gene symbol
        gene_symbols.append(gene_symbol)
    fileinput.close()
    return gene_symbols


Entrez_ids = mg.querymany(get_gene_symbols(), scopes='symbol', fields='entrezgene', species='human', as_dataframe=True)


# set as_dataframe to True will return a pandas dataframe object

Entrez_ids.to_csv(sys.stdout, sep="\t")  # write the dataframe to stdout

# sys.stdout.write()  expects the character buffer object

Entrez_ids.to_csv("Entrez_ids.txt", sep="\t")    # write the pandas dataframe to csv

我的问题是,如果我使用Entrez_ids.to_csv(“Entrez_ids.txt”,sep =“\ t”),结果文件将不包括stderr,如'finished ...),但Entrez_ids.to_csv(sys .stdout,sep =“\ t”)将打印出stderr消息和数据帧。

如果我使用Entrez_ids.to_csv(sys.stdout,sep =“\ t”),如何重定向stderr? 谢谢!

1 个答案:

答案 0 :(得分:1)

这可以帮到你:

In python, can I redirect the output of print function to stderr?

import sys
sys.stderr = to_your_file_object

您可以使用devnull来抑制输出:

import os
f = open(os.devnull,"w")
sys.stderr = f