【python】Linux环境上如何在某种模式中发送命令并得到回显,请大神们帮忙~
比如Linux环境上有模式A,在A模式中可以输入某些命令,比如show BB:
Linux# A #输入A进入模式A
A# show BB #在A模式中输入对应的命令
问题:在python中怎么发送A模式命令并得到回显?
我用subprocess实现,效果如下:
import subprocess
subprocess.call("A",shell=True)
subprocess.call("show BB",shell=True)
在这里就报错了,直接进入到了A模式,show BB根本发送不了,请大神们帮忙看看怎么实现?谢谢了! Python Linux
[解决办法]
A模式类似于mysql这种 用mysql命令进入mysql的终端后输入sql语句这种情况?
[解决办法]
你这个用subprocess实现不了吧,好像pexpect可以干这个,交互的
[解决办法]
subprocess.Popen有参数stdin,stdout,stderr,把它们设为PIPE,即可通过对应的pipe与进程通信。
例子,要在subprocess中运行的命令如下:
#! /bin/bash
while read x
do
if [[ -z $x ]]
then break
else echo $x
fi
done
/tmp/ bash /tmp/echoing
123
123
456
456
456789
456789
/tmp/
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]: