繁体   English   中英

Python-通过终端与开放程序对话

[英]Python - Talking to an open program through terminal

我一直在使用os.system()与终端进行通信,效果很好。 但是,使用它我正在打开一个程序,该程序需要向其中写入命令,并且我不确定如何执行此操作。

基本上,我正在跑步:

tleap -f leaprc

这将在终端中打开程序,并显示:

*non-important code*
>

现在,我需要开始向程序发送命令,但是找不到任何要写在>右边的东西。 os.system()对此不起作用,并且不精通Python,我一无所知。

您可以尝试使用subprocess.Popen

这是一些使用python作为程序的示例代码。

>>> p = subprocess.Popen(['python'],stdin = subprocess.PIPE,stdout = subprocess.PIPE)
>>> p.stdin.write('print "Hello, world!"\n')
>>> p.stdin.write('for i in range(10):\n    print i\n')
>>> p.communicate()
('Hello, world!\r\n0\r\n1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n', None)

如果您在Linux上运行,则将命令发送到终端的最简单方法是使用shlex.split函数。 所以你会打电话

p = subprocess.Popen(shlex.split('tleaf -f leaprc'),stdin = subprocess.PIPE,stdout = subprocess.PIPE)

至少以我的经验,在过程对象上调用communicate可以将其关闭,因此您只有一次机会可以读取输出。 如果您pexpect ,我将研究pexpect模块。

或者尝试使用python-pexpect包代替Subprocess 更加轻松友好。

import pexpect

mypassword='somepassword'

child = pexpect.run('passwd guille') child.expect('Password:')
child.sendline(mypassword)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM