def _subprocess_check(self, subprocess): subprocess.wait() if subprocess.returncode in [0, 2, 3]: pass else: raise RuntimeError("Process returned: %s" % (subprocess.communicate()[1].decode("utf-8")))
async def run(ctx, *, code): if "while True:" in code: await ctx.send(embed=discord.Embed( title= ":warning: Take Note An Infinite Loop will not produce any result", colour=discord.Colour.red())) if "input" in code: await ctx.send(embed=discord.Embed( title= ":warning: Take Note No inputs will/can be entered in.\nTherefore, no results will be given.", colour=discord.Colour.red())) async with ctx.typing(): place = open("placeholder.py", "w") place.write( f"from discord.ext import commands\nclient = commands.Bot('def ')\nfrom datacord import *\n{code}\nimport os\nclient.run(os.getenv('bot-token'))" ) place.close() import subprocess subprocess = subprocess.Popen("python placeholder.py", shell=True, stdout=subprocess.PIPE) output, error = subprocess.communicate() subprocess_return = output.decode('utf-8') embed = discord.Embed(title=ctx.author.name, description=f"Code Input:\n```{code}```", colour=discord.Colour.purple()) embed.set_footer(text="Another Discord Bot by @Fishball_Noodles#7209") embed.add_field(name="Code Output", value=f"```\n{subprocess_return}\n```") if error != None: embed.add_field(name="Error:", value=f"```{error}```") await ctx.send(embed=embed)
def sendAudioStream(self): self.ffmpegSubprocess = sp.Popen(' '.join(self.audio_send_command), stdout=sp.PIPE, stderr=sp.PIPE, shell=True, preexec_fn=os.setsid) out, err = sp.communicate() print(out)
def start_telasocial(): try: #dont need to fork python subprocess.Popen('startx /usr/lib/taboca/telasocial/telasocial',shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) #workaround to wait X to be started to grab its pid sleep(5) logging.info('TelaSocial started with PID: ' + grab_pid()) except: logging.error('Impossible to start X and Telasocial: ' + subprocess.communicate()[0])
def detectIfRedisNeedToDie(): import subprocess print('Killing redis server') subprocess = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE) output, error = subprocess.communicate() target_process = 'redis-server' for line in output.splitlines(): if target_process in str(line): pid = int(line.split(None, 1)[0]) os.kill(pid, 9)
def start_telasocial(): try: alive = urllib2.urlopen("http://"+SERVER_ADDRESS+"/control/server.txt") is_ok = alive.read() logging.info('Is ok? '+is_ok) #dont need to fork python subprocess.Popen('/usr/lib/taboca/telasocial/telasocial',shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) #workaround to wait X to be started to grab its pid sleep(5) logging.info('TelaSocial started with PID: ' + grab_pid()) except: logging.error('Impossible to start X and Telasocial: ' + subprocess.communicate()[0])
def _subprocess_check(self, subprocess): subprocess.wait() no_error_codes = [ ExitCodes.OK, ExitCodes.NO_TEMPLATE, ExitCodes.UNKNOWN_TARGET ] if subprocess.returncode in no_error_codes: pass else: comm = subprocess.communicate() raise RuntimeError( "Process returned: %s" % (comm[0].decode("utf-8") + comm[1].decode("utf-8")))
def start_telasocial(): try: #dont need to fork python subprocess.Popen('startx /usr/lib/taboca/telasocial', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) #workaround to wait X to be started to grab its pid sleep(5) logging.info('TelaSocial started with PID: ' + grab_pid()) except: logging.error('Impossible to start X and Telasocial: ' + subprocess.communicate()[0])
def doEnableSection(self, sections): cmd = [ "pkexec", "software-properties-gtk", "-e", "%s" % ' '.join(sections) ] try: output = subprocess.communicate(cmd, stdout=subprocess.PIPE, universal_newlines=True) except (OSError, subprocess.CalledProcessError) as e: print("Execution failed: %s" % e, file=sys.stderr) return True # FIXME: Very ugly, but gksu doesn't return the correct exit states if not output.startswith("Enabled the "): return False return True
def end_process(self, subprocess, signal=signal.SIGSTOP): print('ending process pid', subprocess.pid) try: process = psutil.Process(subprocess.pid) except psutil.NoSuchProcess: print('process already stopped:', subprocess.pid) return command = process.cmdline() if 'ffmpeg' in command: print('ending ffmpeg recording gracefully') #subprocess.terminate() end_recording = subprocess.communicate(input=b'q') #print(end_recording) else: subprocess.terminate() self.running_processes.remove(subprocess) return
def pingScan(self): print(colors["BLUE"], "Scanning {}".format(self.ipAddr), colors["END"]) process = subprocess.Popen(["/bin/ping", "-c 1 ", self.ipAddr], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = subprocess.communicate(input=None) if "bytes from " in stdout: print( colors["YELLOW"], "The IP Address {} has responded with an Echo Reply".format( stdout.split()[1]), colors["END"]) else: print(colors["RED"], "No Echo Response!", colors["END"]) sys.exit()
def _communicate(cmd, subprocess): stdout, stderr = subprocess.communicate() if subprocess.returncode: print >>sys.stderr, "*-*-*- ERROR", str(subprocess.returncode), "calling hudson" print >>sys.stderr, stderr
projects_list = ','.join(maven_projects_dir_in_run_order) maven_arguments.extend(['--projects', projects_list]) maven_arguments.extend(shlex.split(maven_lifecycle_arguments)) log.info('final maven arguments are %s', maven_arguments) try: os.chdir(source_base_dir) pOpenParams = [] pOpenParams.append(maven_executable) pOpenParams.extend(maven_arguments) log.debug('pOpen arguments are : %s', str(pOpenParams)) process = subprocess.Popen(pOpenParams, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, error = subprocess.communicate() log.info(output) log.warn(error) except(IOError, OSError) as err: log.error("Error while running maven: %s", str(err)) else: err_msg = 'Something is not right unable to setup the environment' log.error(err_msg) sys.exit(err_msg) else: print("Base directory \ Drive unmapped : " + base_dir + ".... Exiting NOW!")
def _get_list_from_subprocess(self, subprocess): self._subprocess_check(subprocess) text = subprocess.communicate()[0].decode("utf-8") return [os.path.abspath(line) for line in text.split("\n") if line]
#!/usr/bin/env python from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select from selenium.common.exceptions import NoSuchElementException import unittest, time, re import subprocess pwd = subprocess.communicate("ls") print pwd class LoginPrimary(unittest.TestCase): def setUp(self): self.driver = webdriver.Firefox() self.driver.implicitly_wait(30) self.base_url = "https://trials.aminocom.com/" self.verificationErrors = [] self.accept_next_alert = True def test_login_primary(self): driver = self.driver driver.get("https://trials.aminocom.com") driver.maximize_window() driver.find_element_by_id("username").clear() driver.find_element_by_id("username").send_keys("rayres") driver.find_element_by_id("username").send_keys(u"\ue004") driver.find_element_by_id("userpassword").clear() driver.find_element_by_id("userpassword").send_keys("planet07")
def todays_ctr(db, date): query = {"date": date} result = db.ctr_global.find_one( query) # Find the row corresponding to today's CTR return result if __name__ == "__main__": config = load_config() db = get_mongo_db(config["db"]["host"], config["db"]["port"], config["db"]["name"]) # Get prod MongoDB date = str(datetime.date.today()) # Get today's date result = todays_ctr(db, date) if "num_recommends" not in result: sys.exit() # No recommendations made today so far if "num_clicks" not in result: # No clicks yet today send_ctr_alert(date, 0) sys.exit() ctr = round(result["num_clicks"] / result["num_recommends"], 3) # Compute CTR if ctr < MIN_CTR: process = subprocess.Popen([ "/bin/bash", "/home/localuser/PRODTeam1_RS/deployments/rollback.sh" ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) subprocess.communicate() # Call rollback script send_ctr_alert(date, ctr)
filename_protein_wc = extract_top_folder + top_protein_wc_filename tmp_filename = 'tmp.csv' auc_filename = 'auc' print(write_mean_filename) df_lig = load_df_feather(write_mean_filename) print(df_lig.head()) print((df_lig['target'] == 1).sum()) acc_group = df_lig.groupby(['acc', 'MHC_mol']) #acc_group = df_lig.groupby(['source']) filename_tmp = auc_folder + tmp_filename for context in ['wc', 'uc']: aucs = list() for c, acc in enumerate(acc_group): acc[1][['target', f'Prediction_{context}']].to_csv(filename_tmp, header=None, index=False, sep='\t') run = ['roc', '-t', '0.5', filename_tmp] process = Popen(run, universal_newlines=True, stdout=PIPE, stderr=PIPE) stdout, stderr = process.communicate() aucs.append(stdout.split('\n')[-2].split()[2]) print(acc[0], aucs[-1]) filename_auc = auc_folder + auc_filename aucs_np = np.array(aucs, dtype='float') print(context, np.mean(aucs_np)) np.save(filename_auc + '_' + context, aucs_np)
"mn --topo linear,2,2", "to be filled", "h1s1 ip a", "h2s1 ip a", "h1s1 iperf -s &", "h2s1 iperf -s &" ] #command to create topology temp1 = commands[0] temp2 = temp1.split() subprocess.call(temp2) #command to call POX controller #command to read ip address of first server temp1 = commands[2] temp2 = temp1.split() subprocess_output = subprocess.Popen(temp2, stdout=subprocess.PIPE) ip_first_server = subprocess.communicate() ip_first_server = str(ip_first_server) ip_first_server = parse_ip_addr_output(ip_first_server) #command to read ip address of second server temp1 = commands[3] temp2 = temp1.split() subprocess_output = subprocess.Popen(temp2, stdout=subprocess.PIPE) ip_second_server = subprocess.communicate() ip_second_server = str(ip_second_server) ip_second_server = parse_ip_addr_output(ip_second_server) #command to run first server temp1 = commands[4] temp2 = temp1.split() subprocess.call(temp2)
parser.add_argument('--port', type=int, default=9999, help='The port to listen on') parser.add_argument('--controller_ip', default='192.168.4.1', help='The controller ip address') parser.add_argument('--controller_port', type=int, default=9998, help='The port that the controller is listening on') parser.add_argument('--ledplay_ip', default='192.168.4.1', help='The LED Play ip address') parser.add_argument('--ledplay_port', type=int, default=1234, help='The port that the LED Play application is listening on') parser.add_argument('--ledplay_startup', required=False, type=int, default=60, help='Time to wait before LEDPlay starts up') parser.add_argument('--config', required=False, type=str, default='tidessensorosc/supervision.json') parser.add_argument('--disable_sun', dest='disable_sun', action='store_true') parser.add_argument('--disable_sound', dest='disable_sound', action='store_true') parser.add_argument('--kill_existing', dest='kill_existing', action='store_true') parser.set_defaults(disable_sun=False, disable_sound=False, kill_existing=False) args = parser.parse_args() if args.kill_existing: subprocess = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE) output, error = subprocess.communicate() this_pid = os.getpid() target_process = "python" for line in output.splitlines(): if target_process in str(line): pid = int(line.split(None, 1)[0]) if pid != this_pid: logger.warning('Killing existing python processes') os.kill(pid, 9) with open(args.config, 'r') as file: supervision = json.load(file) battery_state_pin = DigitalInputDevice(supervision['battery_state_pin'], pull_up=True) charger_pin = DigitalOutputDevice(supervision['charger_pin']) charger_state_pin = DigitalInputDevice(supervision['charger_state_pin'], pull_up=True) power_pin = DigitalOutputDevice(supervision['power_pin'])
] p_pdf = sp.Popen(cmd_pdf, stdout=sp.PIPE) cmd_sf = ["python", "graphics/plot_sf.py", str(run), str(number)] p_sf = sp.Popen(cmd_sf, stdout=sp.PIPE) (out_sf, err_sf) = p_sf.communicate() (out_pdf, err_pdf) = p_pdf.communicate() pdf_status = p_pdf.wait() print("pdfs done.") sf_status = p_sf.wait() print("sfs done.") if os.path.exists(traj_path): os.remove(traj_path) print("trajs removed.") print("Iterations done. Doing last step") cmd_pdf = [ "python", "graphics/plot_pdfs.py", str(run), str(number), "--read_gen" ] sp.Popen(cmd_pdf, stdout=sp.PIPE) (out, err) = sp.communicate() print(out, err) cmd_sf = ["python", "graphics/plot_sf.py", str(run), str(number), "--read_gen"] sp.Popen(cmd_sf, stdout=sp.PIPE) (out, err) = sp.communicate() print(out, err)