2011-02-12 124 views
0

我希望我的程序默认为标准输出,但可以选择将其写入文件。我应该创建自己的打印功能并调用那个有输出文件的测试,或者有更好的方法吗?这对我来说似乎效率低下,但我可以想到的每种方式都会为每次打印呼叫调用附加的测试。我知道从长远来看,这真的不重要,至少在这个剧本中,但我只是想学习好的习惯。处理输出重定向的最佳方式是什么?

回答

2

写入文件对象,并且当程序启动时,该对象指向sys.stdout或指向用户指定的文件。

Mark Byers的答案更像unix,大多数命令行工具只使用stdin和stdout,并让用户按照他们认为合适的方式进行重定向。

+0

谢谢,这可能是我会做的。 – kryptobs2000 2011-02-13 00:35:30

4

只需用print打印标准即可。如果用户希望将输出重定向到一个文件,他们可以这样做:

python foo.py > output.txt 
+0

优秀的一点,我没有想到这一点。但是,我仍然不能这样做,因为我也打印状态消息到stdout,我不想进入该文件。 – kryptobs2000 2011-02-13 00:34:04

+1

@ kryptobs2000:你知道状态和错误信息存在stderr,不是吗?将状态消息发送到`sys.stdout`有什么意义? – tzot 2011-02-19 20:12:16

-1

我的反应将是输出到一个临时文件,然后或者转储到标准输入输出,或将其移动到他们要求的。

0

我建议你使用日志模块和logging.handlers ...流,输出文件等。

0

如果您在使用子模块,然后根据您从您的命令行采取的选项,你可以有一个打开文件对象的stdout选项。这样,从程序内部可以重定向到一个文件。

import subprocess 
with open('somefile','w') as f: 
    proc = subprocess.Popen(['myprog'],stdout=f,stderr=subprocess.PIPE) 
    out,err = proc.communicate() 
    print 'output redirected to somefile' 
1

不,您不需要创建单独的打印功能。在Python 2.6,你有这样的语法:

# suppose f is an open file 
print >> f, "hello" 

# now sys.stdout is file too 
print >> sys.stdout, "hello" 

在Python 3.X:

print("hello", file=f) 
# or 
print("hello", file=sys.stdout) 

所以,你真的没有区分文件和标准输出。他们是一样的。

的玩具例子,它输出“你好”你想要的方式:

#!/usr/bin/env python3 
import sys 

def produce_output(fobj): 
    print("hello", file=fobj) 
    # this can also be 
    # fobj.write("hello\n") 

if __name__=="__main__": 
    if len(sys.argv) > 2: 
     print("Too many arguments", file=sys.stderr) 
     exit(1) 

    f = open(argv[1], "a") if len(argv)==2 else sys.stdout 
    produce_output(f) 

注意,印刷过程抽象它是否与标准输出或文件的工作。

相关问题