2016-08-25 85 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