如果stdin是管道传输,某些交互式命令会以不同方式输出。那是为什么?
下面我在3个不同的命令上测试subprocess.Popen,使用和不使用stdin管道。
的代码:
import subprocess, time
def run_command(command, enable_input):
print 'command="{}", enable_input={}:'.format(command, enable_input)
# Launch the process and set up pipes.
if enable_input:
stdin = subprocess.PIPE
else:
stdin = None
child = subprocess.Popen(command, stdin=stdin)
# Wait a second for output.
time.sleep(1)
# Terminate the child if it hasn't finished.
if child.poll() == None:
child.terminate()
print '\n-----' # Print a separator
commands = ('cmd', 'python', 'timeout 1')
for command in commands:
run_command(command, enable_input=False)
run_command(command, enable_input=True)
的输出:
command="cmd", enable_input=False:
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\>
-----
command="cmd", enable_input=True:
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\>
-----
command="python", enable_input=False:
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
-----
command="python", enable_input=True:
-----
command="timeout 1", enable_input=False:
Waiting for 0 seconds, press a key to continue ...
-----
command="timeout 1", enable_input=True:
ERROR: Input redirection is not supported, exiting the process immediately.
-----
下面链接的问题的答案表明,一些程序试图检测它们是由人类还是脚本运行。这是这种情况吗?如果是这样,他们如何在Windows上检测到它?
Why does supplying stdin to subprocess.Popen cause what is written to stdout to change?
答案 0 :(得分:3)
是的,如果您正在管道或重定向输入,某些程序的行为会有所不同。您可以像这样检测它:
import sys
print sys.stdin.isattty() # True if it's a terminal, False if it's redirected
这适用于* nix以及Windows。