如何在python中将不同的结果打印到屏幕和文件中?

2024-10-01 11:19:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我注意到httpiepython工具在以下两个cae中给出了不同的结果:

  1. $ http google.com
  2. $ http google.com > out.txt

文件out.txt未命中第一种情况下出现的头文件。你知道吗


Tags: 文件工具txtcomhttp头文件google情况
2条回答

使用sys.stdout.isatty判断stdout是终端(“tty”)还是文件,并根据这一点打印不同的输出,例如:

import sys
if sys.stdout.isatty():
    print "Hello terminal!"
else:
    print "Hello non-terminal!"

http的手册页上,您可以找到以下内容

Output options:
  print WHAT, -p WHAT

   String specifying what the output should contain:

   'H' request headers 'B' request body 'h' response headers 'b' response body

   The default behaviour is 'hb' (i.e., the response headers  and  body  is 
   printed), if standard  output  is  not redirected. If the output is piped
   to another program or to a file, then only the response body is printed by
   default.

这表明http在重定向输出时故意表现出不同的行为。要获得与未重定向输出相同的行为,可以使用

`http  print hb google.com > out.txt`

(但还要注意,漂亮的打印与重定向的行为不同。)

相关问题 更多 >