Show command prompt in tkinter window - python

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!!

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('\n')[-2]
if command == 'exit':
exit()
cmd.insert('end', f'\n{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

Related

Unable to run one python script from another python script

I'm trying to run one script from another script. I've read; What is the best way to call a script from another script? and I can't seem to get this to work.
My main script (Script A) does a lot of image processing and GUI interactions. However, randomly an error message or other window might appear interrupting the GUI interactions until the message or window is closed.
I've written a second script (Script B) that I want to run perpetually that closes these windows or error messages when discovered.
I'm trying to call Script B from Script A like this:
import close_windows
close_windows.closeWindows
print("Starting Close Windows....")
And Script B is:
import pyautogui as py
def closeWindows():
image = r'C:\image.jpg'
image2 = r'C:\image2.jpg'
while True:
foundimage = py.locateCenterOnScreen(image)
foundimage2 = py.locateCenterOnScreen(image2)
if foundimage or foundimage2 != None:
py.click(1887, 65)
When I run script B independently it works, when I try running it via Script A with close_windows.closeWindows nothing happens.
I've also tried from close_windows import closeWindows and calling closeWindows but again, nothing happens.

How to remove "press enter to continue" when running Powershell within Python

Edited* Solution: Remove "pause".
I'm running a python script which calls upon powershell to execute a line of code:
def download():
subprocess.call('C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe yt-dlp https://www.youtube.com/watch?v=jtjnnykvnh4;pause', shell=True)
download()
The problem was that after executing, it would output "Press Enter to continue..." This interrupts the program.*in my original example I forgot to include the ";pause" which is what turned out to be what was causing the interruption in the program, as kindly pointed out by the marked answer.
Below is the fixed line of code which does not prompt "press enter to continue" after running:
def download():
subprocess.call('C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe yt-dlp https://www.youtube.com/watch?v=jtjnnykvnh4;kill $pid', shell=True)
download()
Apologies for confusion caused by the original post. Thanks for the help.
PowerShell normally exits unless you specify -NoExit at the commandline. Even then it will not include the message you are seeing unless you add a pause at the end instead. Even so, I would expect your command to look more like
'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe & {yt-dlp https://www.youtube.com/watch?v=jtjnnykvnh4}'
My guess this has more to do with Python, though I have not encountered it before...have you tried executing the PowerShell line from another commandline (cmd on Windows or bash on Linux/Mac or another favourite) to verify that you get the same result independently of Python?
Another possibility is that it is the yt-dlp tool that you are using that has the pause effect (I am not familiar with the tool). Is it a PowerShell module? Or is it something that can be run on the commandline and you don't need PowerShell as a middleman anyway? Would it have a "silent" or "-q" argument, or another more relevant argument?

pyautogui.click() doesn't work as expected

Actually, I have written a code where I've to lunch the application such that I've to click the on-screen keyboard using this pyautogui.click(). But it is not working on on-screen keyboard. I'll be pleased to have your precious opinion. Thanks in advance.
import os
import pyautogui as pg
import time
x= 195
y=505
secret="secretpassword"
command = "application"
os.system(command)
pg.click(x, y)
pg.typewrite(secret)
pg.typewrite(["enter"])
If the application is already lunched this is working but i want to lunch it with os.system(command)
and after that enter my password and access to the application.
Am I doing something wrong ?
I changed
os.system(command)
with
subprocess.Popen(command)
Now it's working
subprocess.Popen() is strict super-set of os.system().
os.system() will block and wait for the application to exit.
This means that your click, in fact, will not execute until the opened appication closes.
To verify this, you can open a (python) shell and run following code:
import os
import pyautogui
def test():
os.system('<something simple opening a window>')
pyautogui.typewrite("I'm in the shell again!")
test()
To run your script as you want, use os.popen, or, even better, subprocess.Popen. These will run the command without blocking.
If you do this, keep in mind your application will have startup time, so you will want to wait some time after the call as noted in the comments under your question.

Python Pinging -t

I have a batch program that simply pings in loop with 'ping adress -t'. Adress being whatever I'm trying to ping at the time.
I'd like to do something similiar with python, but without the popup of a command prompt window and thus I'd like to avoid anything that would do this. I want a way to print it ONLY to the python window, so I can use it in my Tkinter program.
This is what I would originially thought would work, and it does, but I want the output to be in the python window, not in the command prompt.
import subprocess
subprocess.call(["ping", "google.com", "-t"])
What about:
import subprocess
subprocess.call(["ping", "-t"])

How to open a powershell terminal with one python script?

I am working on a text based game that I run by double clicking on my top level script namely TopLevel.py.
I am looking for a way to open two terminals in this script. In the one terminal the main game will be run where damage is done and spells are used etc. In the other terminal I would like to display a list of commands that the user can type in , and I want the latter one to stay there and not close until the game is finished. I am not going to show you the whole top level script (it is too long) but this is basically what I want to achieve:
def displayCommands(hero):
list_of_commands = []
#this contains all my commands that the user can type in
def main():
hero = Hero() #make hero instance
enemy = Enemy() #make and enemy instance
a_game = TopLevel(hero,enemy) #create game engine
a_game.play() #start game
#implement code here to open another terminal
#and display user commands in there
Is there a way that I can open another terminal in this script and pass the displayCommands() function as a parameter to display its contents in the second terminal? Any help will be appreciated :)
It's possible for one Python script to spawn another that will run in parallel with it via subprocess. The spawned process can then display any text piped to it (via normal print statements or calls) in a simple tkinter-based window -- see the errorwindow module in this answer of mine for more information.
It likely doesn't matter how the original script gets started. I personally have used it both in ones that were started from a command shell as well as from other tkinter based applications -- so starting yours from powershell should be fine. The module's original author was using Linux or something similar, I believe.
You should convert your second program to .exe first,the one will display user commands. Say you saved it as usercommands.exe, after then in your main script use this to open that;
import subprocess
subprocess.Popen([r"usercommands.exe"],
creationflags=subprocess.CREATE_NEW_CONSOLE)
It'll open another console window that runs usercommands.exe when you run your main file.
Notes;
They must be in the same directory, your main file and .exe file
usercommands.exe must show the commands in an infinite loop(while True), so it's
going to display commands untill the user close it.
Edit;
Now, we have some spells and usercommands will have to use that spell variables after then show us some combinations. For doing this, we have to import your first file to usercommands script.It's going to like this;
usercommands.py
import mainfile #mainfile.py
if choose == mainfile.wizard:
print (something)
if choose == mainfile.subzero:
print (something)
The algorithm should be like this,you will convert usercommands.py to .exe then it will work as you want I guess, we can't now before you try it ;)

Categories