Best Python code snippet using slash
slm.py
Source:slm.py  
...13def main():14    os.system("cls")15    _header()16    17    if _get_argv("check"):18        # check for licenses19        check_licenses()20    if _get_argv("reset"):21        # Reset all licenses22        reset_licenses()23    if _get_argv("get"):24        # get a license25        get_license()26def get_license():27    "Main functionality called by the -get argument"28    # If no licenses are free, tell user and exit29    if get_free_license_list() == []:30        _div()31        print("NO FREE LICENSES AVAILABLE")32        print(" ")33        print("Use -check to check which machines have taken a license or -reset to reset all licenses.")34        print(" ")35        input("Press enter to exit...")36        sys.exit(1)37    else:38        request_license()39def request_license():40    """41    The actual process of requesting a license file, renaming it, pointing the env var to it 42    and launching the application, waiting for it's exit and then resetting the lic.43    """44    licenserepo = _get_argv("licenserepo").replace("\\", "/")45    print("Requesting a license...")46    _dashingLine()47    # check if a used license with current hostname may exist48    used_hostname_lic = check_if_hostname_in_use()49    if used_hostname_lic:50        print("Found a used license for this computer, using the same license instead...")51        use_license(used_hostname_lic)52        53        # set a lock environ so this session wont rename the lic back but ethe original will do that54        os.environ["SLM_MULTIPLE_SESSIONS"] = "True"55    else:56        lic = get_free_license_list()[0]57        ext = None58        if "." in lic:59            ext = lic.split(".")[-1]60        # rename lic file to .inuse.hostname61        lic_path = os.path.join(licenserepo, lic)62        if ext:63            rlic = lic.split("."+ext)[0]64            rlic = rlic+".inuse."+_get_hostname()+"."+ext65        else:66            rlic = lic+".inuse."+_get_hostname()67        rlic_path = os.path.join(licenserepo, rlic)68        # rename69        os.rename(lic_path, rlic_path)70        # use license and start app71        use_license(rlic_path)72def use_license(license_path):73    "Uses the license file specified, sets the env, calls and waits for the application, then resets the license after closing"74    env = _get_argv("env")75    exe = _get_argv("exe")76    args = _get_argv("args")77    78    # set env to rlic path79    os.environ[env] = license_path80    print("Got a license!")81    print("Starting application...")   82    os.system(r'"'+exe+'"')83    if not "SLM_MULTIPLE_SESSIONS" in os.environ:84        # After application closes, reset the license so it's not in use85        print("Detected application close, returning license...")86        reset_licenses(os.path.basename(license_path))87    else:88        print("Not resetting license as multiple sessions are running...")89def check_licenses():90    "Check's the license repo for available licenses and in use licenses"91    env = _get_argv("env")92    licenserepo = _get_argv("licenserepo")93    print("Licenses in use:")94    _dashingLine()95    lics = False96    for lic in os.listdir(licenserepo):97        if ".inuse" in lic:98            print(lic)99            lics = True100    if not lics:101        print("- None")102    print(" ")103    print("Licenses not in use:")104    _dashingLine()105    for lic in os.listdir(licenserepo):106        if not ".inuse" in lic:107            print(lic)108def reset_licenses(license_name=None):109    "Resets a specific license or all licenses in the license repo so they can be picked up again..."110    licenserepo = _get_argv("licenserepo")    111    print(" ")112    print("Resetting licence(s)...")  113    _dashingLine()114    for lic in os.listdir(licenserepo):115        if ".inuse" in lic:116            def reset_lic():117                print("Resetting license: {}".format(lic))118                lic_path = os.path.join(licenserepo, lic)119                ext = lic.split(".")[-1]120                rlic = lic.split(".inuse")[0]121                rlic = rlic+"."+ext122                rlic_path = os.path.join(licenserepo, rlic)123                os.rename(lic_path, rlic_path)124            if license_name:125                # only reset license_name126                if lic.lower() == license_name.lower():127                    reset_lic()128            else:129                # Reset every license130                reset_lic()131    print(" ")132    print("DONE!...")  133def check_if_hostname_in_use():134    "Returns either a path to a license file that has the current hostname in it so we can reuse it, else returns False"135    licenserepo = _get_argv("licenserepo").replace("\\", "/")136    hostname = _get_hostname()137    # check if we are already using a lic with this hostname, then choose that138    for lic in os.listdir(licenserepo):139        if hostname in lic:140            lic_path = os.path.join(licenserepo, lic).replace("\\", "/")141            return lic_path142    return False                143def get_free_license_list():144    "Returns a list of free license files in the licenserepo or an empty list if none are available"145    licenserepo = _get_argv("licenserepo").replace("\\", "/")146    free_lic_list = []147    for lic in os.listdir(licenserepo):148        if not ".inuse" in lic:149            free_lic_list.append(lic)150    return free_lic_list151# Helper functions _152def _div():153    print(" ")154    _paddedLine()155def _paddedLine():156    print("###########################################")157def _dashingLine():158    print("-------------------------------------------")159def _header():160    system("TITLE SIMPLE LICENSE MANAGER")161    _div()162    print("SIMPLE LICENSE MANAGER")163    _paddedLine()164    print(" ")165def _get_argv(argv):166    "Get's a argument from the command line args"167    args = sys.argv168    for arg in args:169        if argv in arg.lower():170            try:171                return arg.split("-"+argv+":")[1]172            except:173                return True174    return None175def _get_hostname():176    return socket.gethostname()177if __name__ == "__main__":...__init__.py
Source:__init__.py  
...81    def __init__(self):82        super(ArcGisProvider, self).__init__()83        self._print_fn = self._print_logo_fn = arcpy.AddMessage84        # output directory must be defined for _cleanup() method85        Globals.outdir = self._get_argv(86            constants.PARAMETER_PATH_TO_OUTPUT_DIRECTORY87        )88        # computation type89        if self._get_argv(constants.PARAMETER_DPRE_ONLY).lower() == 'true':90            self.args.typecomp = CompType.dpre91            self.args.data_file = os.path.join(92                Globals.outdir, 'save.pickle'93            )94        else:95            self.args.typecomp = CompType.full96        # logger97        self._add_logging_handler(98            handler=ArcPyLogHandler(),99            formatter=logging.Formatter("%(levelname)-8s %(message)s")100        )101        102        # define storage writter103        self.storage = ArcGisWritter()104    @staticmethod105    def _get_argv(idx):106        """Get argument by index.107        :param int idx: index108        """109        return sys.argv[idx+1]110    def _load_dpre(self):111        """Run data preparation procedure.112        :return dict: loaded data113        """114        from model.smoderp2d.providers.arcgis.data_preparation import PrepareData115       116        prep = PrepareData(self.storage)...test_main.py
Source:test_main.py  
...19    def test_without_arguments(self):20        sys.stderr = StringIO()21        self.assertRaises(SystemExit, main)22    def test_cmd_status(self):23        argv = self._get_argv('status')24        main(argv=argv, out=self.out)25        output_lines = self.out.getvalue().splitlines()26        self.assertTrue(output_lines[0].startswith(27                        'Instance:i-1111 (name-i-1111) stopped'))28        self.assertTrue(output_lines[1].startswith(29                        'Instance:i-2222 (name-i-2222) stopped'))30    def test_cmd_start(self):31        argv = self._get_argv('start')32        main(argv=argv, out=self.out)33        output_lines = self.out.getvalue().splitlines()34        self.assertTrue(output_lines[0].startswith('Instance:i-1111 running'))35        self.assertTrue(output_lines[1].startswith('Instance:i-2222 running'))36    def test_cmd_stop(self):37        argv = self._get_argv('stop')38        main(argv=argv, out=self.out)39        output_lines = self.out.getvalue().splitlines()40        self.assertTrue(output_lines[0].startswith('Instance:i-1111 stopped'))41        self.assertTrue(output_lines[1].startswith('Instance:i-2222 stopped'))42    def test_cmd_restart(self):43        argv = self._get_argv('restart')44        main(argv=argv, out=self.out)45        output_lines = self.out.getvalue().splitlines()46        self.assertTrue(output_lines[0].startswith('Instance:i-1111 running'))47        self.assertTrue(output_lines[1].startswith('Instance:i-2222 running'))48    def test_cmd_now(self):49        self.out = StringIO()50        argv = self._get_argv('now')51        main(argv=argv, out=self.out)52        output_lines = self.out.getvalue().splitlines()53        self.assertTrue(output_lines[0].startswith(54                        'Instance:i-1111 (name-i-1111) running'))55        self.assertTrue(output_lines[1].startswith(56                        'Instance:i-2222 (name-i-2222) running'))57        instance_ids = self.mock_method.call_args[0][0]58        self.mock_method.return_value = get_instances_mock(instance_ids)59        self.out = StringIO()60        argv = self._get_argv('now')61        main(argv=argv, out=self.out)62        output_lines = self.out.getvalue().splitlines()63        self.assertTrue(output_lines[0].startswith(64                        'Instance:i-2222 (name-i-2222) running'))65        self.assertTrue(output_lines[1].startswith(66                        'Instance:i-1111 (name-i-1111) running'))67    def _get_argv(self, cmd):68        argv = []69        argv.append('--aws-access-key-id=%s' % self.access_key_id)70        argv.append('--aws-secret-access-key=%s' % self.secret_access_key)71        argv.append('--instances=%s' % ','.join(self.instance_ids))72        argv.append(cmd)73        return argv74if __name__ == '__main__':...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!!
