2016-08-25 84 views
0

请帮助我在python中编写简单的控制台应用程序。它应该将所有输入重定向到系统shell(bash或windows cmd或powershell)并将其所有输出都提供给屏幕。 只要我可以说从python应用程序运行终端。与控制台(sh,bash,cmd,powershell)的透明交互

下一个代码,是用一些奇怪的行为:第一个3次后的任何键按下时输出一些以前的命令(可能是从高速缓存)

#!/bin/python3 

import subprocess 
import sys 

proc = subprocess.Popen(['bash']) 
while True: 
    buff = sys.stdin.readline() 
    stdoutdata, stderrdata = proc.communicate(buff) 
    if(stdoutdata): 
     print(stdoutdata) 
    else: 
     print('n') 
     break 
+0

我在发布问题后编写的代码。我明白,没有代码的问题看起来不明显。有问题的时候我还没有想法。 @格雷尔,原谅我,如果这是粗鲁的。 – kyb

+0

@kyb没关系,我现在删除了那个注释,你添加了代码:) – grael

+0

当我用'subprocess.Popen(['cmd])'从Windows PowerShell运行这个脚本时,它可以正常工作。当使用Ctrl + B运行时,Sublime Text显示Linux下和Windows下的黑色死机。 – kyb

回答

0

我想你需要

(执行?) proc = subprocess.Popen(['bash'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

docs

PIPE indicates that a new pipe to the child should be created. DEVNULL indicates that the special file os.devnull will be used. With the default settings of None, no redirection will occur; the child’s file handles will be inherited from the parent.

我不认为你想让你的bash直接连接到你的父进程的stdin。这将解释奇怪。

+0

我试过了。在第一次输入时产生一个错误: 'Traceback(最近调用最后一个): 文件“./devel/python/terminal/terminal2.py”,第11行,在 stdoutdata,stderrdata = proc.communicate(buff) 文件“/usr/lib/python3.5/subprocess.py”,第1072行,在沟通中012​​stdout,stderr = self._communicate(输入,endtime,超时) 文件“/usr/lib/python3.5/subprocess .py“,第1700行,在_communicate中 input_view = memoryview(self._input) TypeError:memoryview:需要一个类似字节的对象,而不是'str' ' – kyb

+0

一些更奇怪的事情 - 不同环境的结果为我工作) – GreenAsJade