简体   繁体   English

从 python 脚本运行外部交互式程序

[英]Running an external interactive program from a python script

I have a python script which tries to execute external programs.我有一个 python 脚本,它试图执行外部程序。 My project involves a python talk bot through which the client should be able to execute commands in the remote terminal.我的项目涉及一个 python 对话机器人,客户端应该能够通过它在远程终端中执行命令。

So basically the module incorporating the talk bot allows me only to get inputs and send output.I need to take the input and see if it is a terminal command and execute it.所以基本上包含谈话机器人的模块只允许我获取输入并发送 output。我需要接受输入并查看它是否是终端命令并执行它。

So I used the subprocess.Popen object to implement this.所以我使用了 subprocess.Popen object 来实现这个。

The problem is, if the command calls a program which is interactive, ie.问题是,如果命令调用一个交互式程序,即。 waits for an input and gives output, I am not able to handle it.等待输入并给出 output,我无法处理它。 In the best case, Popen waits for all inputs and then gives the output.在最好的情况下,Popen 等待所有输入,然后给出 output。

Is there a way to do this properly, ie.有没有办法正确地做到这一点,即。 start an external program and send input, get output;启动外部程序并发送输入,得到output; send input, get output and so on.发送输入,得到 output 等。

In my opinion the best model for this kind of problems is using an asynchronous single-threaded approach, but it requires code that is somewhat complex even with use of helping libraries.在我看来,解决此类问题的最佳 model 是使用异步单线程方法,但即使使用帮助库,它也需要有点复杂的代码。

Something conceptually simpler is the use of a multithread approach概念上更简单的是使用多线程方法

import thread
import sys
import time

def repl():
    while True:
        print ">>> ",
        sys.stdout.flush()
        s = raw_input()
        exec s

def main_thread():
    for i in xrange(30):
        print i
        time.sleep(1)

thread.start_new_thread(repl, ())
main_thread()

In the above code the function repl waits for input and then execs whatever is entered at the prompt, but at the same time the main program is running (here it's not doing anything interesting, just counting up to 30).在上面的代码中,function repl等待输入,然后执行在提示符下输入的任何内容,但同时主程序正在运行(这里它没有做任何有趣的事情,只是数到 30)。

Depending on how complex is your program this can be a reasonable solution.根据您的程序的复杂程度,这可能是一个合理的解决方案。 Note that after a certain level of parallel execution and logic complexity the multithread approach shows some drawback (complex and hard to debug locking logic)请注意,在一定程度的并行执行和逻辑复杂性之后,多线程方法显示出一些缺点(复杂且难以调试锁定逻辑)

pexpect may be what you need. pexpect可能是您需要的。

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

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