Transparent interaction with console (sh,bash,cmd,powershell)

一个人想着一个人 提交于 2020-01-06 15:50:44

问题


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.

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

回答1:


I think you need

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

From the 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.

I don't think you want your bash to be connected to your parent process's stdin directly. That would explain wierdness.



来源:https://stackoverflow.com/questions/39140632/transparent-interaction-with-console-sh-bash-cmd-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!