How to terminate a process with python in Ubuntu? - python

I need to close an .exe at the end of my code. I was able to start the .exe file
proc = subprocess.Popen('.nameProgram.exe')
Now I have to close it but the terminate() function doesn't seem to work.
I tried this code:
proc.terminate()
I noticed that the exe executable is under another java process. How can I close it. Do you have any suggestions? Thanks

Type
ps
In terminal & check on which name program is runing once you run. copy that name.
#inside python program
import os
os.system('pkill programName')

Related

Python opens executable, but it doesn't close on its own

Little background: Code::Blocks is an IDE with a C++ integrated compiler. When creating a C++ project, it creates a .exe file so you can run the project.
So now I want to run that executable file using a Python script (Using VSCode). I tried subprocess.call(), subprocess.run() and subprocess.Popen(), and all of them start the background process, but it doesn't compile, so it just keeps running on the Task Manager. If I run it manually (by double-clicking it) then it opens, it closes and I get my correct answer on the output file.
This is the C++ project folder for the problem "kino" :
This is a photo with the .exe on the Task Manager :
And this is my Python code:
process = subprocess.run([r'C:\Users\Documents\kino\kino.exe'], shell = True)
If you still don't understand my problem, here is a video describing it.
Use pywin32 to get it done.
Something like this will solve your issue
import win32com.client
app = win32com.client.Dispatch("WScript.Shell")
app.Run('Path/Yourexe.exe')
subprocess.run would not capture the output of the spawn process, however there is no reason for it to keep running in background. Try the following example, I just checked this in my linux(with a simple 'hello world' program) so if it does not works for you then it could be OS specific issue.
p = subprocess.Popen(['C:\Users\Documents\kino\kino.exe'], stdout=subprocess.PIPE)
#out, err = p.communicate()
print(p.stdout.read())
The way I solved my problem was by running the executable using the ./ command. So, I did something like
process = subprocess.run('./kino.exe', shell = True)

How to restart other program in python?

I have python script that interacts with other windows program. Occasionally this program crashes and I get an error in script. How can I shut down this program and restart it again?
This code works for me
import subprocess
subprocess.call(["taskkill", "/F", "/T", "/IM", "progname.exe"]) # forced killing, with childs, by name
subprocess.Popen([r"C:\Path\To\Folder\progname.exe", "--fast"])

Check a Python Script Is Running

I have a python script named update.py, and I want to use another python script to check whether the script is running or not. If update.py doesn't run or error, then the script will run update.py.
Can i do it? If there is an example it will be very thankful.
Not sure about what you are asking but as given this may help, so if you just want to call one python script from another then you can use script 1
#!/usr/bin/python
from subprocess import call
call(["python", "update.py"])
Save this file in a script named script1 and run it, it will compile update.py.
If you want to check for any syntax error in update.py then you can use script 2
#!/usr/bin/python
from subprocess import call
call(["python","-m","py_compile", "update.py"])
If script2 compiles without any error then it shows that there is no syntax error in your program.
Thirdly if you want to check if update.py is running currently or not you can use script 3
#!/usr/bin/python
import psutil
import sys
from subprocess import Popen
for process in psutil.process_iter():
if process.cmdline() == ['python', 'update.py']:
sys.exit('Process found: exiting.')
print('Process not found: starting it.')
Popen(['python', 'update.py'])
This last script will tell if your script is running or not and if it is not running it will compile it.
Scripts are generally used for these kinds of tasks. You have a monitor script that keeps track of update.py that keeps running in the background. It becomes easier if monitor script launches the python script in the beginning.
#!/bin/bash
# Monitor script.
EXEC=<path>/update.py
while true; do
"$EXEC" &
wait # Here the assumption is that you want to run this forever.
done

Python: Quit IDLE after Script running

Is it possible to somehow quit Python IDLE under Windows from within my python code/script at the end after running?
I tried something like:
import sys
sys.exit(0) # or exit(1)
didn't work. Probably only quits the current "process" of the running python script.
Thanks a lot
If you can run IDLE from the command line (or edit your shortcut), I found this in the IDLE help.
If IDLE is started with the -n command line switch it will run in a
single process and will not create the subprocess which runs the RPC
Python execution server.
Which seems to imply that the script is running inside IDLE. I did a quick test script, and calling exit() brought up a box asking to kill the program. Clicked yes, and the script and IDLE both quit. Hope that can help.
This will do exactly what you want. No prompt.
import os
os.system("taskkill /f /im pythonw.exe")
To quit Python IDLE under Windows from within a python code/script without a further prompt, try:
parent_pid = os.getppid() # Get parent's process id
parent_process = None
for proc in psutil.process_iter(attrs=['pid']): # Check all processes
if proc.pid == parent_pid: # Parent's Process class
parent_process = proc
break
if parent_process is not None:
parent_process.kill() # Kill the parent's process
This works with IDLE, PyCharm and even the command line in Windows.

How to start child cmd terminals in separate windows, from python script and execute scripts on them?

I have been trying rather unsuccesfully to open several terminals (though one would be enough to start with) from say an ipython terminal that executes my main python script. I would like this main python script to open as many cmd terminals as needed and execute a specific python script on each of them. I need the terminal windows to remain open when the script finishes.
I can manage to start one terminal using the command:
import os
os.startfile('cmd')
but I don't know how to pass arguments to it, like:
/K python myscript.py
Does anyone have any ideas on how this could be done?
Cheers
H.H.
Use subprocess module. Se more info at. Google>>python subprocess
http://docs.python.org/2/library/subprocess.html
import subprocess
subprocess.check_output(["python", "c:\home\user\script.py"])
or
subprocess.call(["python", "c:\home\user\script.py"])

Categories

Resources