37,720
社区成员
发帖
与我相关
我的任务
分享
#! /bin/bash
while read x
do
if [[ -z $x ]]
then break
else echo $x
fi
done
它的作用就是如果输入不为空,则打印该输入,否则终止。在shell中运行如下:
/tmp/ bash /tmp/echoing
123
123
456
456
456789
456789
/tmp/
下面是用subprocess.Popen执行该程序,并通过stdin,stdout与该程序通信的例子:
In [24]: a = subprocess.Popen(['bash', '/tmp/echoing'], stdin = subprocess.PIPE, stdout = subprocess.PIPE) # 建立进程
In [25]: a.stdin.write('123\n') # 输入
In [26]: a.stdout.readline() # 输出
Out[26]: '123\n'
In [27]: a.stdin.write('456') # 输入没有\n结尾,echoing暂时接受不到456,也就没有输出
In [28]: a.stdout.readline() # 因为进程a没有输出,这个语句被block了,只有ctrl-C取消
---------------------------------------------------------------------------
KeyboardInterrupt Traceback (most recent call last)
<ipython-input-28-f95b4fc7f77a> in <module>()
----> 1 a.stdout.readline()
KeyboardInterrupt:
In [29]: a.stdin.write('789\n') # 继续输入789,并回车
In [30]: a.stdout.readline() # 有输出了
Out[30]: '456789\n'
In [31]: a.stdin.write('') # 没有输入
In [32]: a.wait() # a仍在允许,这儿又被block了, ctrl-C取消
---------------------------------------------------------------------------
KeyboardInterrupt Traceback (most recent call last)
<ipython-input-32-eb63b29ac52d> in <module>()
----> 1 a.wait()
/usr/lib/python2.7/subprocess.pyc in wait(self)
1299 if self.returncode is None:
1300 try:
-> 1301 pid, sts = _eintr_retry_call(os.waitpid, self.pid, 0)
1302 except OSError as e:
1303 if e.errno != errno.ECHILD:
/usr/lib/python2.7/subprocess.pyc in _eintr_retry_call(func, *args)
476 while True:
477 try:
--> 478 return func(*args)
479 except (OSError, IOError) as e:
480 if e.errno == errno.EINTR:
KeyboardInterrupt:
In [33]: a.stdout.readline() # 没有输出,无法读取
---------------------------------------------------------------------------
KeyboardInterrupt Traceback (most recent call last)
<ipython-input-33-f95b4fc7f77a> in <module>()
----> 1 a.stdout.readline()
KeyboardInterrupt:
In [34]: a.stdin.write('\n') # 空输入
In [35]: a.wait() # 进程a终止了
Out[35]: 0
In [36]: