Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How do I make a program where I can run a piece of code, then show the results? So if I make my program run python --version it should print something like Python 3.8.3 (depends on what version you are on), but you get the point

PS: I know this has been posted before, but they don't work for me :(

Thanks!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
219 views
Welcome To Ask or Share your Answers For Others

1 Answer

So here I made a very simple version of what You may want (type in python --version to try out):

from tkinter import Tk, Text
import subprocess


def run(event):
    command = cmd.get('1.0', 'end').split('
')[-2]
    if command == 'exit':
        exit()
    cmd.insert('end', f'
{subprocess.getoutput(command)}')


root = Tk()

cmd = Text(root)
cmd.pack()

cmd.bind('<Return>', run)

root.mainloop()

the subprocess.getoutput() gets the output the cmd would give if the given command was used

EDIT (moved comment here):
there are some limitations however for example running pause will just crash tkinter and the output will be given only after command has finished running for example if You tracert google.com it may take a while and during that the window will be unresponsive until it completes the process and then puts it all out (maybe for that it is possible to use threads to not make the window unresponsive at least)

EDIT (28.07.2021.):
Probably better to use subprocess.Popen and stream data from there


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...