Best Python code snippet using ATX
actions.py
Source:actions.py
...115def raw_move_camera(action, world):116 """Move the camera."""117 action_cmd = action.action_raw.camera_move118 world.assign_to(action_cmd.center_world_space)119def raw_cmd(action, ability_id, queued, unit_tags):120 """Do a raw command to another unit."""121 action_cmd = action.action_raw.unit_command122 action_cmd.ability_id = ability_id123 action_cmd.queue_command = queued124 if not isinstance(unit_tags, (tuple, list)):125 unit_tags = [unit_tags]126 action_cmd.unit_tags.extend(unit_tags)127def raw_cmd_pt(action, ability_id, queued, unit_tags, world):128 """Do a raw command to another unit towards a point."""129 action_cmd = action.action_raw.unit_command130 action_cmd.ability_id = ability_id131 action_cmd.queue_command = queued132 if not isinstance(unit_tags, (tuple, list)):133 unit_tags = [unit_tags]...
shell.py
Source:shell.py
1#!/usr/bin/env python3.62import os3import re4import sys5def safe_exec(raw_cmd):6 cmd = tok(raw_cmd)7 # simple single command8 fname = cmd[0]9 args = cmd # By convention args[0] is the filename anyways10 if os.access(fname, os.X_OK): # if we are given a correct full path, why not?11 os.execve(fname, args, os.environ)12 # walk the path13 for directory in re.split(":", os.environ['PATH']):14 program = f"{directory}/{fname}"15 if os.access(program, os.X_OK):16 os.execve(program, args, os.environ)17 # Successful execs never return, they just go missing in action...18 print(f"command not found {fname}")19# Example:20# ls -a -lh --list => ['ls', '-a', '-lh', '--list']21# removes & from strings ls / & => ['ls', '/']22def tok(val):23 val = val.replace("&", "").strip()24 return re.split('\s+', val)25# for redirecting output of command on left side26# eg. ls -lh > file.txt27def exec_oredirect_cmd(raw_cmd, bg):28 raw_cmd = raw_cmd.replace("&", "").strip()29 cmds = re.split(">", raw_cmd)30 try:31 ret_code = os.fork()32 if ret_code == 0: # I am child33 os.close(sys.stdout.fileno())34 sys.stdout = open(cmds[1].strip(), 'w')35 os.set_inheritable(sys.stdout.fileno(), True)36 safe_exec(cmds[0].strip())37 else: # I am parent, fork was ok38 if not bg:39 child_pid = os.wait() # wait for child40 except OSError as e:41 print(f"fork failed with code: {e}")42# for redirecting input of command on right side43# eg. ls -lh < out.txt44def exec_iredirect_cmd(raw_cmd, bg):45 raw_cmd = raw_cmd.replace("&", "").strip()46 cmds = re.split("<", raw_cmd)47 try:48 ret_code = os.fork()49 if ret_code == 0: # I am child50 os.close(sys.stdin.fileno())51 sys.stdin = open(cmds[1].strip(), 'r')52 os.set_inheritable(sys.stdin.fileno(), True)53 safe_exec(cmds[0].strip())54 else: # I am parent, fork was ok55 if not bg:56 os.wait() # wait for child57 except OSError as e:58 print(f"fork failed with code: {e}")59def exec_pipe_cmd(raw_cmd):60 producer, consumer = re.split("\|", raw_cmd)61 pipe_out, pipe_in = os.pipe() # r, w are for reading and writing to the pipe62 try:63 producer_pid = os.fork()64 if producer_pid: # still parent65 consumer_pid = os.fork()66 if consumer_pid: # still parent67 os.close(pipe_in)68 os.close(pipe_out)69 os.waitpid(producer_pid, 0)70 os.waitpid(consumer_pid, 0)71 else: # consumer72 os.dup2(pipe_out, sys.stdin.fileno())73 os.close(pipe_out)74 safe_exec(consumer.strip())75 else: # producer76 os.dup2(pipe_in, sys.stdout.fileno())77 os.close(pipe_in)78 safe_exec(producer.strip())79 except OSError as e:80 print(f"fork failed with code: {e}")81def cd(raw_cmd):82 dr = tok(raw_cmd)[1]83 os.chdir(dr)84def main():85 while True:86 try:87 raw_cmd = input(os.environ['PS1'])88 # raw_cmd = input("$:")89 if raw_cmd == "\n":90 continue91 elif raw_cmd is None:92 continue93 elif raw_cmd == "":94 continue95 elif raw_cmd.strip() == "q":96 return97 elif "cd" in raw_cmd:98 cd(raw_cmd)99 elif ">" in raw_cmd:100 exec_oredirect_cmd(raw_cmd, "&" in raw_cmd)101 elif "<" in raw_cmd:102 exec_iredirect_cmd(raw_cmd, "&" in raw_cmd)103 elif "|" in raw_cmd:104 exec_pipe_cmd(raw_cmd)105 else: # simple command with no redirect106 pid = os.fork()107 if pid: # parent108 if "&" not in raw_cmd:109 os.wait()110 else: # child111 safe_exec(raw_cmd)112 except EOFError:113 sys.exit()114if __name__ == '__main__':...
cups_manager.py
Source:cups_manager.py
1# -*- coding: cp1251 -*-2#!/usr/bin/env python3from subprocess import Popen, PIPE4import re5class CupsManager():6 active = r'active|start|running'7 inactive = r'inactive|stop|waiting'8 def __shell(self, cmd):9 p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)10 out, err = p.communicate()11 msg = out + err12 status = (lambda x: 'ok' if x == '' else 'error')(err)13 return (status, msg)14 def cups_status(self):15 raw_cmd = self.__shell('service cups status')16 if raw_cmd[0] == 'error':17 return raw_cmd18 if len(re.findall(self.active, raw_cmd[1])) > 0:19 return raw_cmd20 if len(re.findall(self.inactive, raw_cmd[1])) > 0:21 return ('error', raw_cmd[1])22 def cups_start(self):23 raw_cmd = self.__shell('service cups start')24 if raw_cmd[0] == 'error':25 return raw_cmd26 if len(re.findall(self.active, raw_cmd[1])) > 0:27 return raw_cmd28 if len(re.findall(self.inactive, raw_cmd[1])) > 0:29 return ('error', raw_cmd[1])30 def cups_restart(self):31 raw_cmd = self.__shell('service cups restart')32 if raw_cmd[0] == 'error':33 return raw_cmd34 if len(re.findall(self.active, raw_cmd[1])) > 0:35 return raw_cmd36 if len(re.findall(self.inactive, raw_cmd[1])) > 0:37 return ('error', raw_cmd[1])38 def cups_stop(self):39 raw_cmd = self.__shell('service cups stop')40 if raw_cmd[0] == 'error':41 return raw_cmd42 if len(re.findall(self.inactive, raw_cmd[1])) > 0:43 return raw_cmd44 if len(re.findall(self.active, raw_cmd[1])) > 0:45 return ('error', raw_cmd[1])46 # @param destination - printer name47 def get_printer_queue(self, destination=None):48 if destination is not None:49 cmd = 'lpq -P %s' % destination50 else:51 cmd = 'lpq'52 return self.__shell(cmd)53 # @param destination - printer name54 # @return tuple (status like "ok" or "error", ip like "socket://xxx.xxx.xxx.xxx:ppppp" or "cnijnet:/MA-CA-DD-RE-SS-00")55 def get_printer_ip(self, destination):56 cmd = "lpstat -v | grep %s | awk '{ print $4 }'" % destination57 return self.__shell(cmd)58 # depend installed nmap (yast -i nmap)59 # @param String ip, String or Int port60 # @return "ok" if nmap installed and status. Parse in status ignore case "open" | "fitered" | "closed" | "host seems down"61 def check_port(self, ip, port):62 cmd = 'nmap -p%s %s' % (port, ip)...
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!!