【问题标题】:redirect API Stderr python重定向 API Stderr python
【发布时间】:2014-09-01 11:56:52
【问题描述】:

我正在使用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") 如何重定向标准错误? 谢谢!

【问题讨论】:

  • 在命令行中,您可以使用python your-file.py 2>error.log.txt 来重定向输出。你还想要别的吗?
  • 谢谢,我知道这个技巧。我做了什么: python my-file.py input.txt 2> /dev/null 但标准错误仍然打印在屏幕上。输入文件是这样的:CCDC83 MAST3 FLOT1 RPL11 ZDHHC20 LUC7L3 SNORD49A CTSH ACOT8,每行一个基因名称。你可以自己测试一下。我认为这是因为 mg.querymany 函数将返回错误消息和数据帧。

标签: python stderr


【解决方案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

【讨论】:

  • 我试过了,但没有用。 Entrez_ids.to_csv(sys.stdout, sep="\t") 会将 mg.querymany 函数返回的错误消息和数据帧写入屏幕。
  • 这是否意味着错误写入标准输出?尝试仅重定向标准输出。
  • 你能告诉我具体怎么做(用代码)吗?谢谢你。我看到了这个 [link]stackoverflow.com/questions/1956142/… 但对我来说似乎有点太高级了。
  • 您可以在调用函数之前使用sys.stdout = f 重定向stdout。如果控制台上没有打印,则表示stdout 上正在打印错误。
猜你喜欢
  • 2021-06-29
  • 2022-01-18
  • 1970-01-01
  • 2018-01-25
  • 2017-01-18
  • 1970-01-01
  • 2014-07-22
  • 1970-01-01
  • 2018-03-20
相关资源
最近更新 更多