从Python程序读取stdin通过terminal中的SSH启动

我有这个小python3脚本test.py

 import sys print('test1') test1 = sys.stdin.read() print('test2') test2 = sys.stdin.read() print(test1) print(test2) 

我想通过ssh远程运行这个脚本,如下所示:

ssh srvid 'cd; python3 test.py'

我希望程序打印test1 ,然后等待input,然后打印test2 ,再等待input。

但行为有些不同:

 ssh srvid 'cd; python3 test.py' hell test1 test2 hell 

程序首先等待input。 我已经进入了hell ,按enter键,然后ctr + d为eof。 脚本没有等待第二个input,并打印出test1test2

看来,标准input/标准输出不知何故被封锁。

我在bash中尝试了同样的例子:

 #!/bin/bash echo "Hello world"; read test; echo "helloworld 2"; read test2; echo $test; echo $test2; 

当我通过ssh调用这个脚本的时候,一切都按照我所期望的那样工作。

有人可以帮我吗?

这是由于stdio缓冲的libc惯例 。 如果stdout是一个tty,它通常是行缓冲的; 完全缓冲,否则。

正如其他人所build议的那样,将-t标志传递给ssh会强制执行psuedo-tty分配,结果会得到行缓冲。

但是,您也可以显式清除stdout以获得类似的结果,如下所示:

 import sys print('test1') sys.stdout.flush() test1 = sys.stdin.readline() # ctrl+d and .read() effectively closes print('test2') # stdin for the duration sys.stdout.flush() test2 = sys.stdin.readline() print(test1) print(test2) # flushing happens implicitly when the stream is closed 

另一个select是,在完全无缓冲模式下用-u标志运行python,如

 ssh srvid 'cd; python3 -u test.py' 

其他的解决方法可以在这个stackoverflow问题中find。


程序首先等待input。 我已经进入了hell ,按enter键,然后ctr + d为eof。 脚本没有等待第二个input,并打印出test1test2

我很确定这个脚本并没有停在第二个input,因为在第一个input过程中你发送了一个EOF。


FWIW,我可能会这样写python,除非你需要多行input。 这是比较你的bash例子,国际海事组织。

 #!/usr/bin/env python3 print('test1') test1 = input() # raw_input() in python 2.x print('test2') test2 = input() print(test1) print(test2)