Best Python code snippet using autotest_python
webapp.py
Source:webapp.py
...8 from daemon.pidfile import PIDLockFile9from wsgiref.simple_server import make_server10from raspiweb import RaspiWeb11DEFAULT_OUT_PATH = os.path.join(os.path.sep, 'tmp', 'raspiweb')12def get_pid_path(args):13 return os.path.join(args.out_dir, 'pid')14def get_log_path(args):15 return os.path.join(args.out_dir, 'log')16def start(app, args):17 if not os.path.exists(args.out_dir):18 os.makedirs(args.out_dir)19 if os.path.exists(get_pid_path(args)):20 if args.ignore_stale_pid:21 os.remove(get_pid_path(args))22 else:23 print >>sys.stderr, '{0}: File exists. Already running?'.format(get_pid_path(args))24 sys.exit(1)25 pid_file = PIDLockFile(get_pid_path(args))26 log_file = open(get_log_path(args), 'a')27 def run():28 httpd = make_server('0.0.0.0', 8000, app)29 httpd.serve_forever()30 if not args.foreground:31 with daemon.DaemonContext(pidfile=pid_file, stdout=log_file, stderr=log_file):32 run()33 else:34 run()35def get_parser():36 parser = argparse.ArgumentParser(description='Run an WSGI application')37 parser = argparse.ArgumentParser()38 parser.add_argument('-v', '--verbose', dest='verbose', action='store_true', default=False)39 parser.add_argument('-d', '--out-dir', dest='out_dir', metavar='output_directory', default=DEFAULT_OUT_PATH,40 help='Direcotry for logs, PID file, etc.',)41 mode = parser.add_subparsers(dest="mode")42 class Args(object):43 def __init__(self, *args, **kwargs):44 self.args = args45 self.kwargs = kwargs46 # args re-used in different subparsers47 foreground = Args('-F', '--foreground', action='store_true', default=False)48 ignore_pid = Args('-i', '--ignore-stale-pid', action='store_true', default=False)49 force = Args('-f', '--force', action='store_true', default=False)50 start = mode.add_parser('start')51 start.add_argument(*foreground.args, **foreground.kwargs)52 start.add_argument(*ignore_pid.args, **ignore_pid.kwargs)53 stop = mode.add_parser('stop')54 stop.add_argument(*force.args, **force.kwargs)55 restart = mode.add_parser('restart')56 restart.add_argument(*foreground.args, **foreground.kwargs)57 restart.add_argument(*ignore_pid.args, **ignore_pid.kwargs)58 restart.add_argument(*force.args, **force.kwargs)59 return parser60def stop(args):61 SIGTERM = 1562 SIGKILL = 963 try:64 os.kill(int(open(get_pid_path(args), 'r').read()), SIGTERM)65 except IOError:66 pass67 except Exception:68 if args.force:69 os.kill(int(open(get_pid_path(args), 'r').read()), SIGKILL)70def main():71 args = get_parser().parse_args()72 if args.mode == 'start':73 raspiweb = RaspiWeb()74 start(raspiweb, args)75 elif args.mode == 'stop':76 stop(args)77 elif args.mode == 'restart':78 stop(args)79 raspiweb = RaspiWeb()80 start(raspiweb, args)81 else:82 raise ValueError('Unknown subcommand "{0}"'.format(args.mode))83if __name__ == '__main__':...
switch.py
Source:switch.py
...13 p = os.path.split(p[0])14 if not p:15 os.mkdir(p)16 return p[0]17def get_pid_path():18 return get_path() + '/tmp/tmp.pid'19def check_pid(pid=0, osname=''):20 if pid is None or pid == 0:21 return False22 wincmd = 'tasklist /FI "PID eq %s" /FI "IMAGENAME eq python.exe "' % str(pid)23 lincmd = 'ps ax |grep %s |grep python' % str(pid)24 cmd, size = (wincmd, 150) if osname == 'Windows' else (lincmd, 20)25 returnstr = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)26 data = returnstr.stdout.read()27 return len(data) > size28def read_pid():29 if os.path.exists(get_pid_path()):30 try:31 with open(get_pid_path(), 'r') as f:32 strpid = f.readline().strip()33 return int(strpid)34 except Exception:35 return None36 return None37def rm_pid():38 if os.path.exists(get_pid_path()):39 os.remove(get_pid_path())40def kill(pid):41 """kill function for Win32"""42 kernel32 = ctypes.windll.kernel3243 handle = kernel32.OpenProcess(1, 0, pid)44 return (0 != kernel32.TerminateProcess(handle, 0))45def check_run():46 pid, osname = get_sysinfo()47 if not os.path.exists(get_pid_path()):48 with open(get_pid_path(), 'w') as f:49 f.write(str(pid))50 return False51 ''' å¼å§æ£æ¥ '''52 rs = check_pid(read_pid(), osname)53 if not rs:54 with open(get_pid_path(), 'w') as f:55 f.write(str(pid))56 return rs57class Control:58 def start(self):59 if check_run():60 print('pro has run')61 else:62 print("going to start the monitor client")63 # exit_flag = False64 Client = client.ClientHandle()65 Client.forever_run()66 def stop(self):67 filePid = read_pid()68 if filePid is not None and filePid > 0:...
t.py
Source:t.py
...13 p = os.path.split(p[0])14 if not p:15 os.mkdir(p)16 return p[0]17def get_pid_path():18 return get_path() + 'tmp.pid'19def check_pid(pid=0, osname=''):20 if pid is None or pid == 0:21 return False22 wincmd = 'tasklist /FI "PID eq %s" /FI "IMAGENAME eq python.exe "' % str(pid)23 lincmd = 'ps ax |grep %s |grep python' % str(pid)24 cmd, size = (wincmd, 150) if osname == 'Windows' else (lincmd, 20)25 returnstr = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)26 data = returnstr.stdout.read()27 return len(data) > size28def read_pid():29 if os.path.exists(get_pid_path()):30 try:31 with open(get_pid_path(), 'r') as f:32 strpid = f.readline().strip()33 return int(strpid)34 except Exception:35 return None36 return None37def rm_pid():38 if os.path.exists(get_pid_path()):39 os.remove(get_pid_path())40def kill(pid):41 """kill function for Win32"""42 kernel32 = ctypes.windll.kernel3243 handle = kernel32.OpenProcess(1, 0, pid)44 return (0 != kernel32.TerminateProcess(handle, 0))45def check_run():46 pid, osname = get_sysinfo()47 if not os.path.exists(get_pid_path()):48 with open(get_pid_path(), 'w') as f:49 f.write(str(pid))50 return False51 ''' å¼å§æ£æ¥ '''52 rs = check_pid(read_pid(), osname)53 if not rs:54 with open(get_pid_path(), 'w') as f:55 f.write(str(pid))56 return rs57class Control:58 def start(self):59 if check_run():60 print('pro has run')61 else:62 print('pro start...')63 time.sleep(1000)64 def stop(self):65 filePid = read_pid()66 if filePid is not None and filePid > 0:67 print('pro has kill %s' % filePid)68 kill(filePid)...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!