I am trying to use a python script to
1) getting the Pid of a java program and,
2) using that pid to run JVMRuntimeClient.class
but nothing is happening
Here is my script:-
import subprocess
import os
process = subprocess.Popen('java -cp .Workspace.TestProject.bin.VirtualMemorySimulatorPart3')
pid=str(process.pid)
os.popen('java .Workspace.TestProject.bin.JVMRuntimeClient -pid' + pid)
print(pid)
exit()
Related
I have actualy python script running on background, you can see how it's displayed when i use command "ps -aux" :
root 405 0.0 2.6 34052 25328 ? S 09:52 0:04 python3 -u /opt/flask_server/downlink_server/downlink_manager.py
i want to check if this script are running from another python script, so i try to us psutil module, but it just detect that python3 are running but not my script precisely !
there is my python script :
import os
import psutil
import time
import logging
import sys
for process in psutil.process_iter():
if process.cmdline() == ['python3', '/opt/flask_server/downlink_server/downlink_manager.py']:
print('Process found: exiting.')
It's look like simple, but trust me, i already try other function proposed on another topic, like this :
def find_procs_by_name(name):
"Return a list of processes matching 'name'."
ls = []
for p in psutil.process_iter(attrs=["name", "exe", "cmdline"]):
if name == p.info['name'] or \
p.info['exe'] and os.path.basename(p.info['exe']) == name or \
p.info['cmdline'] and p.info['cmdline'][0] == name:
ls.append(p)
return ls
ls = find_procs_by_name("downlink_manager.py")
But this function didn't fin my script, it's work, when i search python3 but not the name of the script.
Of course i try to put all the path of the script but nothing, can you please hepl me ?
I resolve the issue with this modification :
import psutil
proc_iter = psutil.process_iter(attrs=["pid", "name", "cmdline"])
process = any("/opt/flask_server/downlink_server/downlink_manager.py" in p.info["cmdline"] for p in proc_iter)
print(process)
I am new to python. I am trying to enter two commands in my script.
1) script filename.txt
2) ssh xyz#xyz.com
My script stops after the 1st command in executed. When I exit out of bash the 2nd command is execute. I tried 2 different scripts both have the same issue.
1) Script-1
import os
import subprocess
from subprocess import call
from datetime import datetime
call (["script","{}.txt".format(str(datetime.now()))])
echo "ssh xyz#xyz.com"
2) Script-2
call (["script","{}.txt".format(str(datetime.now()))])
def subprocess_cmd(command):
process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)
proc_stdout = process.communicate()[0].strip()
print proc_stdout
subprocess_cmd('ssh ssh xyz#xyz.com')
There is a way to start another script in python by doing this:
import os
os.system("python [name of script].py")
So how can i stop another already running script? I would like to stop the script by using the name.
It is more usual to import the other script and then invoke its functions and methods.
If that does not work for you, e.g. the other script is not written in such a way that is conducive to being imported, then you can use the subprocess module to start another process.
import subprocess
p = subprocess.Popen(['python', 'script.py', 'arg1', 'arg2'])
# continue with your code then terminate the child
p.terminate()
There are many possible ways to control and interact with the child process, e.g. you can can capture its stdout and sterr, and send it input. See the Popen() documentation.
If you start the script as per mhawkes suggestion is it a better option but to answer your question of how to kill an already started script by name you can use pkill and subprocess.check_call:
from subprocess import check_call
import sys
script = sys.argv[1]
check_call(["pkill", "-9", "-f", script])
Just pass the name to kill:
padraic#home:~$ cat kill.py
from subprocess import check_call
import sys
script = sys.argv[1]
check_call(["pkill", "-9", "-f", script])
padraic#home:~$ cat test.py
from time import sleep
while True:
sleep(1)
padraic#home:~$ python test.py &
[60] 23361
padraic#home:~$ python kill.py test.py
[60] Killed python test.py
Killed
That kills the process with a SIGKIll, if you want to terminate remove the -9:
padraic#home:~$ cat kill.py
from subprocess import check_call
import sys
script = sys.argv[1]
check_call(["pkill", "-f", script])
padraic#home:~$ python test.py &
[61] 24062
padraic#home:~$ python kill.py test.py
[61] Terminated python test.py
Terminated
That will send a SIGTERM. Termination-Signals
Just put in the name of the program NOT the path to your script.
so it would be
check_call(["pkill", "-f", "MotionDetector.py"])
I'm trying to write some short script in python which would start another python code in subprocess if is not already started else terminate terminal & app (Linux).
So it looks like:
#!/usr/bin/python
from subprocess import Popen
text_file = open(".proc", "rb")
dat = text_file.read()
text_file.close()
def do(dat):
text_file = open(".proc", "w")
p = None
if dat == "x" :
p = Popen('python StripCore.py', shell=True)
text_file.write( str( p.pid ) )
else :
text_file.write( "x" )
p = # Assign process by pid / pid from int( dat )
p.terminate()
text_file.close()
do( dat )
Have problem of lacking knowledge to name proces by pid which app reads from file ".proc".
The other problem is that interpreter says that string named dat is not equal to "x" ??? What I've missed ?
Using the awesome psutil library it's pretty simple:
p = psutil.Process(pid)
p.terminate() #or p.kill()
If you don't want to install a new library, you can use the os module:
import os
import signal
os.kill(pid, signal.SIGTERM) #or signal.SIGKILL
See also the os.kill documentation.
If you are interested in starting the command python StripCore.py if it is not running, and killing it otherwise, you can use psutil to do this reliably.
Something like:
import psutil
from subprocess import Popen
for process in psutil.process_iter():
if process.cmdline() == ['python', 'StripCore.py']:
print('Process found. Terminating it.')
process.terminate()
break
else:
print('Process not found: starting it.')
Popen(['python', 'StripCore.py'])
Sample run:
$python test_strip.py #test_strip.py contains the code above
Process not found: starting it.
$python test_strip.py
Process found. Terminating it.
$python test_strip.py
Process not found: starting it.
$killall python
$python test_strip.py
Process not found: starting it.
$python test_strip.py
Process found. Terminating it.
$python test_strip.py
Process not found: starting it.
Note: In previous psutil versions cmdline was an attribute instead of a method.
I wanted to do the same thing as, but I wanted to do it in the one file.
So the logic would be:
if a script with my name is running, kill it, then exit
if a script with my name is not running, do stuff
I modified the answer by Bakuriu and came up with this:
from os import getpid
from sys import argv, exit
import psutil ## pip install psutil
myname = argv[0]
mypid = getpid()
for process in psutil.process_iter():
if process.pid != mypid:
for path in process.cmdline():
if myname in path:
print "process found"
process.terminate()
exit()
## your program starts here...
Running the script will do whatever the script does. Running another instance of the script will kill any existing instance of the script.
I use this to display a little PyGTK calendar widget which runs when I click the clock. If I click and the calendar is not up, the calendar displays. If the calendar is running and I click the clock, the calendar disappears.
So, not directly related but this is the first question that appears when you try to find how to terminate a process running from a specific folder using Python.
It also answers the question in a way(even though it is an old one with lots of answers).
While creating a faster way to scrape some government sites for data I had an issue where if any of the processes in the pool got stuck they would be skipped but still take up memory from my computer. This is the solution I reached for killing them, if anyone knows a better way to do it please let me know!
import pandas as pd
import wmi
from re import escape
import os
def kill_process(kill_path, execs):
f = wmi.WMI()
esc = escape(kill_path)
temp = {'id':[], 'path':[], 'name':[]}
for process in f.Win32_Process():
temp['id'].append(process.ProcessId)
temp['path'].append(process.ExecutablePath)
temp['name'].append(process.Name)
temp = pd.DataFrame(temp)
temp = temp.dropna(subset=['path']).reset_index().drop(columns=['index'])
temp = temp.loc[temp['path'].str.contains(esc)].loc[temp.name.isin(execs)].reset_index().drop(columns=['index'])
[os.system('taskkill /PID {} /f'.format(t)) for t in temp['id']]
Summary: I am ssh'ing to a remote server and executing a fork1.py script over there which is shown below. But the trouble is that I want the processes to execute in the background, so that I can start multiple services.
I know we can use nohup, etc. but they are not working. Even when I use a & at the end, the process starts, but gets killed when the script terminates.
Here is the code:
import os
import sys
import commands
from var import key_loc
import subprocess
import pipes
import shlex
def check(status):
if status != 0:
print 'Error! '
quit()
else:
print 'Success :) '
file1=open('/home/modiuser/status.txt','a')
file1.write("Success :)\n")
if(sys.argv[1]=="ES"):
os.chdir('/home/modiuser/elasticsearch-0.90.0/bin/')
proc1=subprocess.Popen(shlex.split("nohup ./elasticsearch -p /home/modiuser/es.pid"))
if(sys.argv[1]=="REDIS"):
os.chdir('/home/modiuser/redis-2.6.13/src')
proc2=subprocess.Popen(shlex.split("./redis_ss -p /home/modiuser/redis.pid"))
if(sys.argv[1]=="PARSER"):
proc3=subprocess.Popen(shlex.split("nohup java -jar logstash-1.1.12-flatjar.jar agent -f parser.conf"))
file1=open('/home/modiuser/pid.txt','a')
file1.write("PARSER-"+str(proc3.pid)+"\n")
file1.write(str(proc3.poll()))
file1.close()
if(sys.argv[1]=="SHIPPER_TCP"):
proc4=subprocess.Popen(shlex.split("nohup java -jar logstash-1.1.12-flatjar.jar agent -f shipper_TCP.conf"))
file1=open('/home/modiuser/pid.txt','a')
file1.write("SHIPPER_TCP-"+str(proc4.pid)+"\n")
file1.close()
Where am I going wrong?
just try with
import os
os.system('python program1.py &') #this one runs in the background
os.system('python program2.py') #this one runs in the foreground