Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
import psutil
import sys
MEGABYTE = 1 << 20
p = psutil.Popen(["test.exe", '0.1', sys.argv[1]])
#print(p.get_memory_info())
while (p.is_running()):
print(str(p.get_memory_info()[0] / MEGABYTE)+' '+str(p.get_memory_info()[1] / MEGABYTE))
try:
p.wait(0.01)
except:
pass
def start():
global _stream, _process, _worker_log_filename
if _stream is not None:
return
args = [sys.executable, worker.__file__, str(os.getpid())]
log.info(
"Spawning {0} for tests-{1}:\n\n{2}",
_name,
os.getpid(),
"\n".join(repr(s) for s in args),
)
_process = psutil.Popen(
args, bufsize=0, stdin=subprocess.PIPE, stdout=subprocess.PIPE
)
_stream = messaging.JsonIOStream(_process.stdout, _process.stdin, _name)
event, _worker_log_filename = _stream.read_json()
assert event == "watchdog"
atexit.register(stop)
ram = p.memory_info()[0]*ram_lut['B']
for subproc in p.children(recursive=True):
if not subproc.is_running():
continue
subproc_dict = subproc.as_dict(attrs=['pid',
'name',
'cmdline',
'memory_info'])
if subproc_dict['name'] == 'docker':
call = subproc_dict['cmdline'][-1]
tcmd = psutil.Popen(["docker", "ps", "-q"], stdout=PIPE)
running = tcmd.communicate()[0].decode('utf-8')
running = running.split('\n')
tcmd = psutil.Popen(["docker", "inspect"] + running,
stdout=PIPE, stderr=PIPE)
tinf = json.loads(tcmd.communicate()[0].decode('utf-8'))
for tcon in tinf:
if (tcon.get("Config") and
tcon.get("Config").get("Cmd") and
call in tcon['Config']['Cmd']):
tid = tcon['Id']
tcmd = psutil.Popen([
"docker",
"stats",
tid,
"--no-stream",
"--format",
"'{{.MemUsage}} " +
"{{.CPUPerc}}'"
],
def run_command(cmd: str, data: Optional[str], location: str, chw: bool) -> str:
cwd = os.getcwd()
if location is not None and chw is True:
cwd = location
elif location is not None and chw is False:
cmd = '{0} {1}'.format(cmd, location)
r = Popen(shlex.split(cmd), stdout=PIPE, stdin=PIPE, stderr=PIPE, cwd=cwd)
if data is None:
output = r.communicate()[0].decode('utf-8')
else:
output = r.communicate(input=data)[0]
return output
def run(cmd,shell=False,cwd=None,exe="/bin/sh",clear=False):
if options.verbose: print((cmd.replace("\n"," ")))
if cwd == None:
cwd = os.getcwd()
if shell == False:
cmd = cmd.split()
if clear:
try:
cc = subprocess.Popen("/home/jmbell/src/utils/clearcache") # "sync; echo 3 > /proc/sys/vm/drop_caches"
cc.communicate()
print("Memory cache cleared.")
except:
print("Memory cache not cleared. Do not trust runtime results.")
p = psutil.Popen("/usr/bin/time -p "+cmd, shell=shell, cwd=cwd, executable=exe,stderr=subprocess.PIPE) # ,stdout=subprocess.PIPE, stdin=subprocess.PIPE,
_,err=p.communicate() # write stdout to terminal. only keep timing info.
wt,ut,st = err.strip().split("\n")[-3:] # anything before this is exit status 1 or an actual error.
times = [float(wt.split(" ")[-1]),float(ut.split(" ")[-1]),float(st.split(" ")[-1])]
if options.verbose: print((err.strip()))
return times
gevent.spawn(lambda: psutil.Popen(cmd, stdout=DEVNULL, stderr=DEVNULL)).link(AceProxy.ace)
AceProxy.ace = AceProxy.ace.get(timeout=delay if delay>=0 else 0.5)
def spawn_cmd(name, cmd, capture_output=True, **kwargs):
if capture_output:
outfd, outpath = tmp_file(name + '.stdout.', '.log')
errfd, errpath = tmp_file(name + '.stderr.', '.log')
# everyone can read
ps = psutil.Popen(cmd, stdin=None, stdout=outfd, stderr=errfd, **kwargs)
else:
outpath = ''
errpath = ''
ps = psutil.Popen(cmd, **kwargs)
comment = 'PID %d, stdout %s, stderr %s' % (
ps.pid, os.path.basename(outpath), os.path.basename(errpath))
log(' '.join(cmd), comment=comment)
return (ps, outpath, errpath)
def clear_port(self, port_list):
"""
Kills process on specified ports list, if any.
"""
if not isinstance(port_list, list):
port_list = [port_list]
for port in port_list:
p = psutil.Popen(['lsof', '-i:{}'.format(port), '-t'], stdout=PIPE, stderr=PIPE)
pid = p.communicate()[0].decode()[:-1] # retrieving PID
if pid is not '':
p = psutil.Popen(['kill', pid])
self.log.info('port {} cleared'.format(port))
def _start_process(self, cmd, *args, **kwargs):
"""This method must be executed only when the `_lock` is acquired"""
try:
self._process_children = []
self._process_cmd = cmd
self._process = psutil.Popen(cmd, *args, **kwargs)
except Exception:
return logger.exception('Failed to execute %s', cmd)
return True