在不是`sys.stdin.isatty()`时等待用户输入

时间:2016-09-03 04:17:28

标签: python

当我尝试some cmd | main.py时:

if not sys.stdin.isatty():
    input() # how to wait for user input but not from pipe?

我已阅读Python script not waiting for user input when ran from piped bash script,但我在Windows中找不到/dev/tty在python代码中处理

1 个答案:

答案 0 :(得分:0)

我在Windows中找不到/dev/tty,无法在python代码中处理它。可能是CONCON:

这是我的python脚本,它接受 管道 命令行参数 的任何输入组合作为用户从控制台的 输入

#! python3
# -*- coding: utf-8 -*- 

import sys

argv_tuple = []                                   # command line arguments
for arg in sys.argv:
    argv_tuple.append( arg )

pipe_tuple = []                                   # values from pipeline
if not sys.stdin.isatty():
    for line in sys.stdin:
        pipe_tuple.append( line.replace('\n', '').replace('\r','') )
    sys.stdin = open('CON:', mode='r', encoding=sys.stdin.encoding)

inpt_tuple = []                                   # inputs from the console
invalue = input(' … your input (`Enter` to quit) … ')
while not invalue == '':                  
    inpt_tuple.append( invalue)
    invalue = input(' …                              … ')

#                                                 # publish the results
print( len( argv_tuple), 'arguments:', argv_tuple)
print( len( pipe_tuple), 'pipelines:', pipe_tuple)
print( len( inpt_tuple), 'kbd input:', inpt_tuple)

输出

dir /b py*.py | python_stdin.py a "b & c"
 … your input (`Enter` to quit) … foo
 …                              … bar
 …                              …
3 arguments: ['D:\\bat\\python_stdin.py', 'a', 'b & c']
2 pipelines: ['pythonprint.py', 'python_stdin.py']
2 kbd input: ['foo', 'bar']