与控制台的透明交互(sh、bash、cmd、powershell) [英] Transparent interaction with console (sh,bash,cmd,powershell)
问题描述
请帮我用python编写简单的控制台应用程序.它应该将所有输入重定向到系统 shell(bash 或 windows cmd 或 powershell),并将所有输出提供给屏幕.简单地说,我可以说从 python 应用程序运行终端.
Please help me to write simple console application in python. It should redirect all input to system shell (bash or windows cmd or powershell) and give all their output to the screen. Simply I can say run terminal from python application.
下一个代码有一些奇怪的行为:在按下任何键后的前 3 次它输出(执行?)一些先前的命令(可能来自缓存)
The next code works with some strange behavior: first 3 times after any key pressed it outputs (executes?) some previous commands (may be from cache)
#!/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
推荐答案
我认为你需要
proc = subprocess.Popen(['bash'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
来自文档:
PIPE 表示应该创建一个到孩子的新管道.DEVNULL 表示将使用特殊文件 os.devnull.和默认设置为None,不会发生重定向;孩子的文件句柄将从父级继承.
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 直接连接到父进程的标准输入.这可以解释怪异.
I don't think you want your bash to be connected to your parent process's stdin directly. That would explain wierdness.
这篇关于与控制台的透明交互(sh、bash、cmd、powershell)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!