2014-09-01 70 views
0

我正在使用python包https://pypi.python.org/pypi/mygene 做一些基因id映射。我有下面的代碼:重定向API Stderr python

#! /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」 09月=「\ t」的),結果文件將不包括標準錯誤,如「完.. ),但是Entrez_ids.to_csv(sys.stdout,sep =「\ t」)將輸出stderr消息和數據幀。

如何使用Entrez_ids.to_csv(sys.stdout,sep =「\ t」)重定向stderr? 謝謝!

+0

在命令行,你可以使用'蟒蛇your-file.py 2 > error.log.txt'來重定向輸出。你想要別的嗎? – doptimusprime 2014-09-01 12:00:55

+0

謝謝,我知道這個訣竅。我做了什麼:python my-file.py input.txt 2>/dev/null,但stderr仍然在屏幕上打印出來。輸入文件是這樣的:CCDC83 MAST3 FLOT1 RPL11 ZDHHC20 LUC7L3 SNORD49A CTSH ACOT8每行一個基因名稱。你可以自己測試一下。我認爲這是因爲mg.querymany函數將返回錯誤消息和數據幀。 – crazyhottommy 2014-09-01 13:10:47

回答

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 
+0

我試過了,它沒有工作。 Entrez_ids.to_csv(sys.stdout,sep =「\ t」)會將mg.querymany函數返回的錯誤消息和數據幀寫入屏幕。 – crazyhottommy 2014-09-01 13:46:27

+0

這是否意味着錯誤寫在標準輸出上?嘗試僅重定向標準輸出。 – doptimusprime 2014-09-01 15:29:36

+0

你能告訴我如何做到這一點(與代碼)?謝謝。我看到這個[鏈接] http://stackoverflow.com/questions/1956142/how-to-redirect-stderr-in-python,但它似乎有點太先進了我。 – crazyhottommy 2014-09-02 01:58:23