This question already has answers here:
How to Close a program using python?
(7 answers)
Closed 23 hours ago.
I'm self-studying python so I'm very inexperienced so I hope you guys can help
The specific problem is:
I'm building a voice communication virtual assistant, I have managed to open the application by voice, but can't write the code to close a running application with a specific name.
I tried using the command
send_keys('%{F4}')
and doesn't seem to get the desired result
So is there any other way?
elif "discord" in you:
app = application.Application()
app.start("C://Users//admin//AppData//Local//Discord//Update.exe --processStart Discord.exe")
robot_brain = "runing Discord"
elif you == " exit discord":
send_keys('%{F4}') # close an active window with Alt+F4
robot_brain = " exit discord"
You can also use taskkill.
proc = subprocess.Popen(['taskkill', '/f', '/im', 'program_name.exe'])
assert proc.wait() == 0
You can use a python library called wmi, you can check on how to use it here.
Click here - How to terminate a windows program using python
I hope this is helpful mate.
Hello, im not too sure what the app is (in your code) but you can use the os module to start files and to start a exe and to exit it
example
import os
os.system("C:/Users/username/Downloads/main.exe")
this starts the file (use startfile instead of system if you want to open like a txt or anything not exe file)
their is alot of way to close it heres some usefull links
How to Close a program using python?
https://docs.python.org/3/library/os.html#os.kill
Related
I try to write a programm in python that notifies me, when a shell like cmd gets opened.
Until now I did the following in python.
Check for new starting processes, get the name of the process and check if its name is cmd.exe.
This works if I start a cmd process manually myself.
But it Turns out if i open a shell with subprocess.getoutput(command) from the subprocess library in python there is no shell listed in the prosesses and I also cant see it in taskmanager.
So I assumed its a childprocess of the pythonscripts process running?
My next Idea was to list all the modules a process is using and check for cmd.exe in the modules.
It turns out the pythonscript with subprocess.getoutput(command) does not use cmd.exe in the modules. Strange.
So right now I am not sure how I could detect the shell or if I am even on the right way.
Maybe I need to find the childprocesses of a the pythonprocess? Or is it possible to get a shell without calling cmd.exe I honestly dont know enough about it.
Maybe its better to check for chertain dlls in the used methods by a process?
I also tried to look in the subprocess.py library but it is difficult for me to understand and it seems to atleast pass over cmd as a parameter for subprocess.getoutput() method.
Can somebody help?
Thank you.
UPDATE:
I use this code to detect the process:
import wmi
c = wmi.WMI()
process_watcher = c.Win32_Process.watch_for("creation")
while True:
new_process = process_watcher()
print(new_process.Caption, new_process.ProcessId)
if new_process.Caption =="cmd.exe":
pid = new_process.ProcessID
break
But if I run this code
import subprocess
output = subprocess.getoutput("ipconfig")
print(output)
The only process detected is pythonw.exe
But if I run
import subprocess
while True:
output = subprocess.getoutput("ipconfig")
print(output)
At some point it find cmd.exe.
So I assume that wmi takes to long to detect the process. So cmd is already closed and does not get found.
Any Ideas how to do this a better way?
I didnt know practic version of solution.But you can use pyautogui for it if you want.You can write a program with pyautogui that notifies you when it find cmd logo at task bar.Example:
import pyautogui
cmdlogo = pyautogui.locateOnScreen('get screenshot of cmd logo and write file name here example:'cmd.png'')
While True:
if cmdlogo:
print('write here what yo want to say when it finds cmd')
else:
pyautogui.sleep(5)
This question already has answers here:
How to clear the interpreter console?
(31 answers)
Closed 2 years ago.
So I have an odd bug which instead of making console clear writes that character.
That issue doesn't occur in C, and everything works normally when I write cls in command prompt window. (I am not an advanced programmer, but I suppose that system() is related with it.)
Edit: (When I use clear, it does completely nothing.) Perhaps that problem is not related to wrong keyword (I use Windows), it just didn't do what I was expecting because of drawing that weird arrow character.
Edit2: I reinstalled whole vs with phyton, and it doesn't worked
Edit3: resolved : "Windows Command Prompt shortcut doesn't work correctly (Ctrl + L)
from os import system
while True :
print(" #")
system("cls")
try this function to clear the screen regardless of OS
from os import system, name
def clear():
if name == 'nt':
x = system('cls')
else:
x = system('clear')
or you could try using subprocess:
from subprocess import call
def clear():
x = call('clear' if os.name =='posix' else 'cls')
Other than that I think it would be some problem with your terminal
So I have been trying to use Python pywin32 package to send inputs to an interactive console based win32 exe which gives me a bunch of options when executed and based on the input keyed in by the user subsequent menus are displayed. After some reading around on the net I did try to execute the following code but it is still unable to send the input to the program, so if anyone has been able to achieve something similar, please let me know.
the code I have been trying is as follows:
import win32com.client
def main():
shell = win32com.client.Dispatch("WScript.Shell")
shell.run('cmd /K cd "E:\\Documents and Settings\\Owner\\Desktop\\pds\\" && CONVERT.EXE')
shell.AppActivate('E:\\Documents and Settings\\Owner\\Desktop\\pds\\CONVERT.EXE')
print("sending keys...")
shell.SendKeys("trial.bin")
shell.SendKeys("{ENTER}")
if __name__ == '__main__':
main()
I've made small improvement in pywinauto library. Now it can deal with console window like so:
import pywinauto
app = pywinauto.Application.start('cmd.exe', wait_for_idle=False)
app.Window_().TypeKeys('cmd.exe /?{ENTER}', with_spaces=True, pause=0.1)
app.Window_().TypeKeys('{ENTER 7}', pause=0.1)
I am very new to python.. I used the code
x = input(" Hey what is your name " )
print(" Hey, " + x)
input(" press close to exit ")
Because i have looked for this problem on internet and came to know that you have to put some dummy input line at the end to stop the command prompt from getting closed but m still facing the problem.. pls Help
I am using python 3.3
On windows, it's the CMD console that closes, because the Python process exists at the end.
To prevent this, open the console first, then use the command line to run your script. Do this by right-clicking on the folder that contains the script, select Open console here and typing in python scriptname.py in the console.
The alternative is, as you've found out, to postpone the script ending by adding a input() call at the end. This allows the user of the script to choose when the script ends and the console closes.
That can be done with os module. Following is the simple code :
import os
os.system("pause")
This will generate a pause and will ask user to press any key to continue.
[edit: The above method works well for windows os. It seems to give problem with mac (as pointed by ihue, in comments). The thing is that "os" library is operating system specific and some commands might not work with one operating system like they work in another one.]
For Windows Environments:
If you don't want to go to the command prompt (or work in an environment where command prompt is restricted), I think the following solution is gooThe solution I use is to create a bat file.
Use notepad to create a text file. In the file the contents will look something like:
my_python_program.py
pause
Then save the file as "my_python_program.bat" - DO NOT FORGET TO SELECT "All Files!
When you run the bat file it will run the python program and pause at the end to allow you to read the output. Then if you press any key it will close the window.
Just Add Simple input At The End Of Your Program it Worked For Me
input()
Try it And It Will Work Correctly
Try this,
import sys
status='idlelib' in sys.modules
# Put this segment at the end of code
if status==False:
input()
This will only stop console window, not the IDLE.
This question already has answers here:
How to keep a Python script output window open?
(27 answers)
Closed 8 years ago.
Is there any way I can stop python.exe from closing immediately after it completes? It closes faster than I can read the output.
Here is the program:
width = float(input("Enter the width: "))
height = float(input("Enter the height: "))
area = width * height
print("The area is", area, "square units.")
You can't - globally, i.e. for every python program. And this is a good thing - Python is great for scripting (automating stuff), and scripts should be able to run without any user interaction at all.
However, you can always ask for input at the end of your program, effectively keeping the program alive until you press return. Use input("prompt: ") in Python 3 (or raw_input("promt: ") in Python 2). Or get used to running your programs from the command line (i.e. python mine.py), the program will exit but its output remains visible.
Just declare a variable like k or m or any other you want, now just add this piece of code at the end of your program
k=input("press close to exit")
Here I just assumed k as variable to pause the program, you can use any variable you like.
For Windows Environments:
If you don't want to go to the command prompt (or work in an environment where command prompt is restricted), I think the following solution is better than inserting code into python that asks you to press any key - because if the program crashes before it reaches that point, the window closes and you lose the crash info. The solution I use is to create a bat file.
Use notepad to create a text file. In the file the contents will look something like:
my_python_program.py
pause
Then save the file as "my_python_program.bat"
When you run the bat file it will run the python program and pause at the end to allow you to read the output. Then if you press any key it will close the window.
Auxiliary answer
Manoj Govindan's answer is correct but I saw that comment:
Run it from the terminal.
And got to thinking about why this is so not obvious to windows users and realized it's because CMD.EXE is such a poor excuse for a shell that it should start with:
Windows command interpreter copyright 1999 Microsoft
Mein Gott!! Whatever you do, don't use this!!
C:>
Which leads me to point at https://stackoverflow.com/questions/913912/bash-shell-for-windows
It looks like you are running something in Windows by double clicking on it. This will execute the program in a new window and close the window when it terminates. No wonder you cannot read the output.
A better way to do this would be to switch to the command prompt. Navigate (cd) to the directory where the program is located and then call it using python. Something like this:
C:\> cd C:\my_programs\
C:\my_programs\> python area.py
Replace my_programs with the actual location of your program and area.py with the name of your python file.
Python files are executables, which means that you can run them directly from command prompt(assuming you have windows). You should be able to just enter in the directory, and then run the program.
Also, (assuming you have python 3), you can write:
input("Press enter to close program")
and you can just press enter when you've read your results.
In windows, if Python is installed into the default directory (For me it is):
cd C:\Python27
You then proceed to type
"python.exe "[FULLPATH]\[name].py"
to run your Python script in Command Prompt