Best Python code snippet using sure_python
test.py
Source:test.py  
...HP_Utility.py
Source:HP_Utility.py  
1import os2import sys3import subprocess4import stat5import platform6import time7import distro8from language import Language9# noinspection PyExceptClausesOrder10class Utility:11    """12    Utility class holds all the working functions!13    """14    @staticmethod15    def is_root():16        """17        if the current user has root privileges or not!18        :return: boolean19        """20        is_root = False21        try:22            if not os.path.exists('/etc/foo'):23                os.makedirs('/etc/foo')24            else:25                os.rename('/etc/foo', '/etc/bar')26            is_root = True27        except IOError as e:28            if 'Permission denied' in str(e):29                print("You need root permissions to do this (O_o)")30            Utility().terminate("Permission Denied!")31        finally:32            if os.path.exists('/etc/foo'):33                os.rmdir('/etc/foo')34            if os.path.exists('/etc/bar'):35                os.rmdir('/etc/bar')36            return is_root37    @staticmethod38    def system_upgrade(is_test=False):39        """40        :param is_test -> if true, upgrade command will run in force yes mode.41        run system update upgrade before doing anything.42        :return:43        """44        return_code = 20045        error_message = ""46        try:47            file_status = os.stat('bash_scripts/updater.sh')48            os.chmod('bash_scripts/updater.sh',49                     file_status.st_mode | stat.S_IEXEC)50            result = subprocess.Popen(51                ['./bash_scripts/updater.sh', str(is_test)])52            result.communicate()53            return_code = result.returncode54            del file_status55            del result56        except IOError as error:57            return_code = 25558            error_message = str(error)59        except subprocess.CalledProcessError as error:60            return_code = 25561            error_message = str(error)62        except OSError as error:63            return_code = 25564            error_message = str(error)65        except KeyboardInterrupt as error:66            return_code = 25567            error_message = str(error)68        finally:69            if return_code != 0:70                # error occurred in the process71                Utility().terminate("Error Code --> " + str(return_code) + " " + error_message)72            return return_code73    @staticmethod74    def install_psql(is_test=False):75        """76        Install Postgresql and Metasploit Framework related stuff77        :return: 0 on success78        """79        return_code = 20080        error_message = ""81        try:82            file_status = os.stat('bash_scripts/psql.sh')83            os.chmod('bash_scripts/psql.sh',84                     file_status.st_mode | stat.S_IEXEC)85            result = subprocess.Popen(['./bash_scripts/psql.sh', str(is_test)])86            result.communicate()87            return_code = result.returncode88            del result89            del file_status90        except IOError as error:91            return_code = 25592            error_message = str(error)93        except subprocess.CalledProcessError as error:94            return_code = 25595            error_message = str(error)96        except OSError as error:97            return_code = 25598            error_message = str(error)99        except KeyboardInterrupt as error:100            return_code = 255101            error_message = str(error)102        finally:103            if return_code != 0:104                Utility().terminate("Error Code --> " + str(return_code) + " " + error_message)105            return return_code106    @staticmethod107    def install_metasploit(is_test=False):108        """109        installs metasploit framework in the system.110        :param is_test: :bool111        :return: :Integer | exit value112        """113        return_code = 200114        error_message = ""115        try:116            metasploit = os.stat('bash_scripts/metasploit.sh')117            os.chmod('bash_scripts/metasploit.sh',118                     metasploit.st_mode | stat.S_IEXEC)119            if distro.linux_distribution(False)[0] == 'kali':120                result = subprocess.Popen(121                    ['./bash_scripts/metasploit.sh', 'Kali', str(is_test)])122            else:123                result = subprocess.Popen(124                    ['./bash_scripts/metasploit.sh', 'Linux', str(is_test)])125            result.communicate()126            return_code = result.returncode127            del result128            del metasploit129        except IOError as error:130            return_code = 255131            error_message = str(error)132        except subprocess.CalledProcessError as error:133            return_code = 255134            error_message = str(error)135        except OSError as error:136            return_code = 255137            error_message = str(error)138        except KeyboardInterrupt as error:139            return_code = 255140            error_message = str(error)141        finally:142            if return_code != 0:143                Utility().terminate("Error Code --> " + str(return_code) + " " + error_message)144            return return_code145    @staticmethod146    def chmod_scripts():147        """148        Installing scripts and apps inside /opt/149        :return:150        """151        return_code = 0152        error_message = ""153        try:154            file_status = os.stat('bash_scripts/install_scripts.sh')155            os.chmod('bash_scripts/install_scripts.sh',156                     file_status.st_mode | stat.S_IEXEC)157            del file_status158        except IOError as error:159            return_code = 255160            error_message = str(error)161        except subprocess.CalledProcessError as error:162            return_code = 255163            error_message = str(error)164        except OSError as error:165            return_code = 255166            error_message = str(error)167        except KeyboardInterrupt as error:168            return_code = 255169            error_message = str(error)170        finally:171            if return_code != 0:172                Utility().terminate("Error Code --> " + str(return_code) + " " + error_message)173            return return_code174    @classmethod175    def terminate(cls, message=None):176        """177        force the python script before exiting178        :param message: exit message179        :return: none180        """181        sys.exit(message)182    @classmethod183    def baby_step(cls, is_test=False):184        """185        baby step takes care of the installing scripts186        :param is_test: boolean187        :return:188        """189        return_code = 0190        error_message = ""191        language = Language()192        first_time = language.main_menu_v2()  # since there is no last item193        print(first_time)194        try:195            while True:196                user_input = input("Your option:: ")197                if user_input == "14":198                    # terminate the loop199                    time.sleep(3)200                    print(language.line_apprx + '\n' + language.line_apprx201                          + '\n' + language.line_thats_wrap + '\n'202                          + language.line_apprx + '\n' + language.line_apprx)203                    sys.exit(0)  # The END204                elif user_input == "13":205                    # install all206                    return_code = Utility.__do_it_all(is_test)207                    if return_code != 0:208                        Utility().terminate("System terminated!")209                    else:210                        time.sleep(3)211                        print(language.line_apprx + '\n' + language.line_apprx212                              + '\n' + language.line_thats_wrap + '\n'213                              + language.line_apprx + '\n' + language.line_apprx)214                else:215                    time.sleep(5)216                    result = subprocess.Popen(217                        ['./bash_scripts/install_scripts.sh', str(is_test), user_input])218                    result.communicate()219                    return_code = result.returncode220                    del result221                    if return_code != 0:222                        Utility().terminate("System terminated!")223                current_menu = language.main_menu_v2()224                print(current_menu)225        except subprocess.CalledProcessError as error:226            return_code = 255227            error_message = str(error)228        except OSError as error:229            return_code = 255230            error_message = str(error)231        except KeyboardInterrupt as error:232            return_code = 255233            error_message = str(error)234        finally:235            if return_code != 0:236                Utility().terminate("System terminated! " + str(error_message))237    @classmethod238    def __do_it_all(cls, is_test=False):239        """240        do it install all the scripts in a linear fashion.241        :param is_test: bool242        :return: integer (success = 0, failure = 255)243        """244        return_code = 0245        error_message = None246        for user_input in range(1, 14):247            try:248                time.sleep(2)249                result = subprocess.Popen(250                    ['./bash_scripts/install_scripts.sh', str(is_test), str(user_input)])251                result.communicate()252                return_code = result.returncode253                del result254                if return_code != 0:255                    Utility().terminate("System terminated!")256            except subprocess.CalledProcessError as error:257                return_code = 255258                error_message = str(error)259            except OSError as error:260                return_code = 255261                error_message = str(error)262            except KeyboardInterrupt as error:263                return_code = 255264                error_message = str(error)265            finally:266                if return_code != 0:267                    Utility().terminate("System terminated! " + str(error_message))268        return return_code269def main():270    language = Language()271    util = Utility()272    if util.is_root():273        if platform.system() != 'Linux':274            print(language.line_hashes + '\n' + language.line_hashes)275            sys.stderr.write(language.line_non_linux_distro)276            print(language.line_hashes + '\n' + language.line_hashes)277            sys.exit(255)278        if sys.version_info < (3, 0, 0):279            print(language.line_hashes + '\n' + language.line_hashes)280            sys.stderr.write(language.line_not_python3)281            print(language.line_hashes + '\n' + language.line_hashes)282            sys.exit(255)283        if distro.linux_distribution(False)[0] != 'kali':284            print(language.line_apprx + '\n' +285                  language.line_not_kali + '\n' + language.line_apprx)286        time.sleep(5)287        # call the utility functions288        util.system_upgrade()289        util.install_psql()290        util.install_metasploit()291        util.chmod_scripts()292        util.baby_step()293    else:294        print(language.line_hashes + '\n' + language.line_hashes +295              '\n' + language.line_non_superuser)296        sys.exit("Permission Denied!\n{}\n{}".format(297            language.line_hashes, language.line_hashes))298if __name__ == '__main__':...cdif2rsf.py
Source:cdif2rsf.py  
1# !/usr/bin/python2import os3from os import EX_OK, EX_USAGE, EX_UNAVAILABLE, EX_IOERR4import sys5##6# $Rev: 1155 $:     Revision of last commit7# $Author: bdubois $:  Author of last commit8# $Date: 2007-05-03 07:51:55 +0200 (Thu, 03 May 2007) $:    Date of last commit9##10def convertToRsf(cdif_input_file_name, rsf_output_file_name):11	print "Reading from file", cdif_input_file_name + "..."12	13	print "\tFiles...",14	return_code = os.system("python ./writeFiles.py " + cdif_input_file_name)15	if return_code == EX_OK:16		print "[ok]"17	else:18		print "[failed]"19		return EX_UNAVAILABLE20	21	print "\tIncludes...",22	return_code = os.system("python ./writeIncludes.py " + cdif_input_file_name)23	if return_code == EX_OK:24		print "[ok]"25	else:26		print "[failed]"27		return EX_UNAVAILABLE28		29	print "\tConditional Compilation...",30	return_code = os.system("python ./writeCondComp.py " + cdif_input_file_name)31	if return_code == EX_OK:32		print "[ok]"33	else:34		print "[failed]"35		return EX_UNAVAILABLE36	37	print "\tClasses...",38	return_code = os.system("python ./writeClasses.py " + cdif_input_file_name)39	if return_code == EX_OK:40		print "[ok]"41	else:42		print "[failed]"43		return EX_UNAVAILABLE44	45	#print "\tTypeDefs...",46	#return_code = os.system("python ./writeTypedefs.py " + cdif_input_file_name)47	#if return_code == EX_OK:48	#	print "[ok]"49	#else:50		print "[failed]"51		return EX_UNAVAILABLE52	53	print "\tInheritance...",54	return_code = os.system("python ./writeInheritance.py " + cdif_input_file_name)55	if return_code == EX_OK:56		print "[ok]"57	else:58		print "[failed]"59		return EX_UNAVAILABLE60	61	print "\tMethods...",62	return_code = os.system("python ./writeMethods.py " + cdif_input_file_name)63	if return_code == EX_OK:64		print "[ok]"65	else:66		print "[failed]"67		return EX_UNAVAILABLE68	69	print "\tAttributes...",70	return_code = os.system("python ./writeAttributes.py " + cdif_input_file_name)71	if return_code == EX_OK:72		print "[ok]"73	else:74		print "[failed]"75		return EX_UNAVAILABLE76	77	print "\tFunctions...",78	return_code = os.system("python ./writeFunctions.py " + cdif_input_file_name)79	if return_code == EX_OK:80		print "[ok]"81	else:82		print "[failed]"83		return EX_UNAVAILABLE84	85	print "\tGlobalVariables...",86	return_code = os.system("python ./writeGlobalVar.py " + cdif_input_file_name)87	if return_code == EX_OK:88		print "[ok]"89	else:90		print "[failed]"91		return EX_UNAVAILABLE92	93	print "\tAccesses...",94	return_code = os.system("python ./writeAccesses.py " + cdif_input_file_name)95	if return_code == EX_OK:96		print "[ok]"97	else:98		print "[failed]"99		return EX_UNAVAILABLE100	101	print "\tInvocations...",102	return_code = os.system("python ./writeInvocations.py " + cdif_input_file_name)103	if return_code == EX_OK:104		print "[ok]"105	else:106		print "[failed]"107		return EX_UNAVAILABLE108		109	print "\tAnnotations...",110	return_code = os.system("python ./writeAnnotations.py " + cdif_input_file_name)111	if return_code == EX_OK:112		print "[ok]"113	else:114		print "[failed]"115		return EX_UNAVAILABLE116	117	print "\tSize and Complexity Metrics...",118	return_code = os.system("python ./writeMetrics.py " + cdif_input_file_name)119	if return_code == EX_OK:120		print "[ok]"121	else:122		print "[failed]"123		return EX_UNAVAILABLE124		125	print "\tChange Frequency Metrics...",126	return_code = os.system("python ./writeCFMetrics.py " + cdif_input_file_name)127	if return_code == EX_OK:128		print "[ok]"129	else:130		print "[failed]"131		return EX_UNAVAILABLE132	133	print "Merging output...",134	return_code = os.system("python ./makeRsf.py " + rsf_output_file_name)135	if return_code == EX_OK:136		print "[ok]"137	else:138		print "[failed]"139		return EX_UNAVAILABLE140	141	remove_command = "rm -f 	accessesWithIDs.txt attributeBelongsToClass.txt \142								attributeHasClassAsType.txt attributesWithIDs.txt \143								classBelongsToFile.txt classesWithIDs.txt \144								conditionalCompilationBlocks.txt typedefsWithIDs.txt\145								fileBelongsToModule.txt filesWithIDs.txt \146								invokableEntityBelongsToFile.txt functionsWithIDs.txt \147								globalVarsWithIDs.txt globalVarHasClassAsType.txt \148								accessibleEntityBelongsToFile.txt \149								inheritanceWithIDs.txt invocationsWithIDs.txt \150								methodBelongsToClass.txt methodsWithIDs.txt \151								modulesWithIDs.txt metricsWithIDs.txt \152								moduleBelongsToModule.txt includeBelongsToFile.txt \153								methodHasClassAsReturnType.txt functionHasClassAsReturnType.txt \154								entityBelongsToBlock.txt methodVisibility.txt \155								methodSignature.txt attributeSignature.txt attributeVisibility.txt\156								accessesLocations.txt invocationLocations.txt \157								defsWithAssociation.txt cfMetricsWithIDs.txt \158								leftValueAccesses.txt annotations.txt \159								annotationBelongsToEntity.txt"160	161	return_code = os.system(remove_command)162	if return_code != EX_OK:163		print "Error cleaning up."164		return EX_IOERR165		166	print "Output written to", rsf_output_file_name167	168	return EX_OK169if __name__ == '__main__':170	if len(sys.argv) < 2:171	  print "Usage:",sys.argv[0],"cdif-input-file-name rsf-output-file-name"172	  sys.exit(EX_USAGE)173	174	input_file=sys.argv[1]175	176	cdif_input_file_name = sys.argv[1]177	rsf_output_file_name = sys.argv[2]178	179	exitCode = convertToRsf(cdif_input_file_name, rsf_output_file_name)180	...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!!
