├── LICENSE ├── README.md ├── Section 1 └── 5.Document-to-install-and-use-atom-editor.txt ├── Section 10 └── 6.Document-search-a-file.py ├── Section 11 ├── 1.Document-check-given-path-is-file-dir-path.py ├── 2.Document-read-a-path-and-identify-files-and-dirs.py ├── 4.Document-read-string-print-with-index-values.py ├── 5.Document-find-all-files.py ├── 8.Document-introduction-to-while.py └── 9.Document-control-statements.py ├── Section 12 └── 2.Document-delete-all-files-which-are-older-than-x-days.py ├── Section 13 ├── 1.Document-introduction-to-subprocess.txt ├── 2.Document-find-java.py └── 3.Document-get-bash-version.py ├── Section 14 ├── 1.Document-create-a-file.py └── 2.Document-s-d.py ├── Section 15 ├── 1.Document-read-csv-file.py ├── 2.Document-read-a-header-and-finding-no-of-rows.py └── 3.Document-create-csv-file.py ├── Section 16 └── working-with-json-files.py ├── Section 17 ├── 1.Document-.working-with-exceptions.py ├── 2.Document-exception-handling-for-known-exceptions.py ├── 3.Document-differce-finally-esle.py └── 4.Document-custom-exceptions.py ├── Section 18 ├── 1.Document-run-your-commands.py ├── 10.variable-leng-keyword.py ├── 12.Document-change-working-dir.py ├── 2.Document-defining-fun.py ├── 3.Documnet-converting-into-fun.py.py ├── 4.Document-scope-of-the-variables.py ├── 5.Document-function-with-simple-arguments.py ├── 6.Document-fun-with-arg-return-values.py ├── 7.Document-fun-with-default-arguments.py ├── 8.Document-function-with-keyword-based-arguments.py └── 9.Document-functions-with-variable-length-argument.py ├── Section 19 ├── 2.Document-0regexe-pat-rules-creation.py ├── 3.Document-rules-2.py ├── 4.Document-rules-3.py ├── 5.Document-regex-flags.py ├── 6.Document-search-and-match-practice.py ├── 7.Document-find-all-find-iter.py └── 9.Document-complie-operations.py ├── Section 20 ├── 1.Document-working-with-remote-linux-from-windows.py └── 2.Document-transfer_files.py ├── Section 21 └── shutil-part-1.py └── Section 22 ├── 1.Document-introduction_to_oops.py ├── 2.Document-working_on_attributes.py ├── 3.Document-using_init_method.py ├── 4.1.Document-without_oops.py ├── 4.2.Document-working_with_oops.py ├── 5.Document-constructor_and_destructor_of_an_object.py ├── 6.1.Document-polymorphism.py ├── 6.2.Document-inheritance.py └── 7.Document-Encpasulation.py /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Packt 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | # Complete-Python-Scripting-for-Automation 5 | Complete Python Scripting for Automation by Packt Publishing 6 | -------------------------------------------------------------------------------- /Section 1/5.Document-to-install-and-use-atom-editor.txt: -------------------------------------------------------------------------------- 1 | open browser 2 | enter url: atom.io 3 | download option --> download atom , it is a .exe 4 | then double click on that, and wait some time. 5 | 6 | install "script" package on your atom. 7 | 8 | go to --> File --> settings --> install --> search with script , scirpt package --> install it 9 | 10 | 11 | and use ctrl+shift+b to run code -------------------------------------------------------------------------------- /Section 10/6.Document-search-a-file.py: -------------------------------------------------------------------------------- 1 | import os 2 | import string 3 | import platform 4 | req_file=input("Enter your file name to search: ") 5 | 6 | if platform.system()=="Windows": 7 | pd_names=string.ascii_uppercase 8 | vd_names=[] 9 | for each_drive in pd_names: 10 | if os.path.exists(each_drive+":\\"): 11 | #print(each_drive) 12 | vd_names.append(each_drive+":\\") 13 | print(vd_names) 14 | for each_drive in vd_names: 15 | for r,d,f in os.walk(each_drive): 16 | for each_f in f: 17 | if each_f==req_file: 18 | print(os.path.join(r,each_f)) 19 | else: 20 | for r,d,f in os.walk("/"): 21 | for each_file in f: 22 | if each_file==req_file: 23 | print(os.path.join(r,each_file)) 24 | -------------------------------------------------------------------------------- /Section 11/1.Document-check-given-path-is-file-dir-path.py: -------------------------------------------------------------------------------- 1 | #This is a platform independet script(you can run on any operating system) 2 | import os 3 | path=input("Enter your path: ") 4 | 5 | if os.path.exists(path): 6 | print(f"Given path : {path}is a valid path") 7 | if os.path.isfile(path): 8 | print("and it is a file path") 9 | else: 10 | print("and it is a directory path") 11 | else: 12 | print(f"Given path : {path} is not existing on this host") -------------------------------------------------------------------------------- /Section 11/2.Document-read-a-path-and-identify-files-and-dirs.py: -------------------------------------------------------------------------------- 1 | ''' 2 | import os 3 | import sys 4 | path=input("Enter your directory path: ") 5 | if os.path.exists(path): 6 | df_l=os.listdir(path) 7 | else: 8 | print("please provide valid path") 9 | sys.exit() 10 | 11 | 12 | print(df_l) 13 | p1=os.path.join(path,df_l[0]) 14 | p2=os.path.join(path,df_l[1]) 15 | 16 | if os.path.isfile(p1): 17 | print(f"{p1} is a file") 18 | else: 19 | print(f"{p1} is a directory") 20 | 21 | if os.path.isfile(p2): 22 | print(f"{p2} is a file") 23 | else: 24 | print(f"{p2} is a directory") 25 | ''' 26 | 27 | 28 | 29 | ''' 30 | print("befor loop") 31 | 32 | for each in [2,3,4,5]: 33 | print("hello",each) 34 | 35 | 36 | print("after loop") 37 | ''' 38 | 39 | import os 40 | import sys 41 | path=input("Enter your directory path: ") 42 | if os.path.exists(path): 43 | df_l=os.listdir(path) 44 | else: 45 | print("please provide valid path") 46 | sys.exit() 47 | 48 | 49 | list_of_files_dir=os.listdir(path) 50 | print("all files and dirs: ",list_of_files_dir) 51 | for each_file_or_dir in list_of_files_dir: 52 | f_d_p=os.path.join(path,each_file_or_dir) 53 | if os.path.isfile(f_d_p): 54 | print(f'{f_d_p} is a file') 55 | else: 56 | print(f'{f_d_p} is a directory') 57 | -------------------------------------------------------------------------------- /Section 11/4.Document-read-string-print-with-index-values.py: -------------------------------------------------------------------------------- 1 | usr_str=input("Enter your string: ") 2 | 3 | index=0 4 | for each_char in usr_str: 5 | print(f'{each_char} -->{index}') 6 | index=index+1 -------------------------------------------------------------------------------- /Section 11/5.Document-find-all-files.py: -------------------------------------------------------------------------------- 1 | #!/usr/local/bin/python3 2 | import os 3 | req_path=input("Enter your directory path: ") 4 | #req_ex=input("Enter the required files extention .py/.sh/.log/.txt: ") 5 | 6 | if os.path.isfile(req_path): 7 | print(f"The given path {req_path} is a file. Please pass only directory path") 8 | else: 9 | all_f_ds=os.listdir(req_path) 10 | if len(all_f_ds)==0: 11 | print(f"The given path is {req_path} an empty path") 12 | else: 13 | req_ex=input("Enter the required files extention .py/.sh/.log/.txt: ") 14 | req_files=[] 15 | for each_f in all_f_ds: 16 | if each_f.endswith(req_ex): 17 | req_files.append(each_f) 18 | if len(req_files)==0: 19 | print(f"There are no {req_ex} files in the logcation of {req_path}") 20 | else: 21 | print(f"There are {len(req_files)} files in the location of {req_path} with an extention of {req_ex}") 22 | print(f"So, the files are: {req_files}") 23 | -------------------------------------------------------------------------------- /Section 11/8.Document-introduction-to-while.py: -------------------------------------------------------------------------------- 1 | ''' 2 | while True: 3 | print("Welcome to loops") 4 | print("............................") 5 | ''' 6 | ''' 7 | import time 8 | while True: 9 | print("MOnitoring file system usage") 10 | time.sleep(1) 11 | ''' 12 | 13 | 14 | ''' 15 | value=4 16 | while value<=6789: 17 | print(value) 18 | value=value+456 19 | ''' 20 | 21 | ''' 22 | cnt=1 23 | while cnt <=5: 24 | print("hello") 25 | cnt=cnt+1 26 | 27 | ''' -------------------------------------------------------------------------------- /Section 11/9.Document-control-statements.py: -------------------------------------------------------------------------------- 1 | ''' 2 | for each in [3,4,56,7,8]: 3 | print(each) 4 | if each==56: 5 | break 6 | 7 | 8 | print("after loop") 9 | ''' 10 | ''' 11 | paths=['/usr/bin','/usr/bin/httpd','/home/users/xyz/weblogic/config.xml'] 12 | for each_path in paths: 13 | print("now working on: ",each_path) 14 | if 'httpd' in each_path: 15 | print(each_path) 16 | break 17 | print("outside of for loop") 18 | ''' 19 | 20 | ''' 21 | cnt=1 22 | while True: 23 | print(cnt) 24 | if cnt==100: 25 | break 26 | cnt=cnt+1 27 | 28 | ''' 29 | 30 | 31 | ''' 32 | 33 | for each in range(1,11): 34 | if each ==7: 35 | continue 36 | print("this is the line inside of your if condition after continue keyword") 37 | print(each) 38 | ''' 39 | 40 | 41 | ''' 42 | if True: 43 | pass 44 | ''' 45 | ''' 46 | for each in range(3): 47 | pass 48 | ''' 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /Section 12/2.Document-delete-all-files-which-are-older-than-x-days.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import datetime 4 | req_path=input("Enter your path: ") 5 | age=3 6 | if not os.path.exists(req_path): 7 | print("Please provide valid path ") 8 | sys.exit(1) 9 | if os.path.isfile(req_path): 10 | print("Please provide directory path ") 11 | sys.exit(2) 12 | today=datetime.datetime.now() 13 | for each_file in os.listdir(req_path): 14 | each_file_path=os.path.join(req_path,each_file) 15 | if os.path.isfile(each_file_path): 16 | file_cre_date=datetime.datetime.fromtimestamp(os.path.getctime(each_file_path)) 17 | #print(dir(today-file_cre_date)) 18 | dif_days=(today-file_cre_date).days 19 | if dif_days > age: 20 | print(each_file_path,dif_days) 21 | 22 | -------------------------------------------------------------------------------- /Section 13/1.Document-introduction-to-subprocess.txt: -------------------------------------------------------------------------------- 1 | import subprocess 2 | sp=subprocess.Popen(cmd,shell=True/False,stdout=subprocess.PIPE,stderr=subprocess.PIPE,universal_newlines=True) 3 | rc=sp.wait() 4 | out,err=sp.communicate() 5 | print(f'OUTPUT IS: {out}') 6 | print(f'Error is: {err}') 7 | ==================================> 8 | if shell=True then your cmd is a string (as your os command) 9 | if shell=False then your cmd is a list 10 | 11 | Note: shell=False dont work on your os environment variables 12 | 13 | ex: cmd="ls -lrt" ==>shell=True 14 | shell=False ==> cmd="ls -lrt".split() or ['ls','-lrt'] 15 | ======================================================================= 16 | 17 | 18 | shell=True always on windows 19 | ============================ 20 | cmd is a string 21 | ---------------------------------------------------------- 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /Section 13/2.Document-find-java.py: -------------------------------------------------------------------------------- 1 | import subprocess 2 | cmd="java -version" 3 | sp=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,universal_newlines=True) 4 | rc=sp.wait() 5 | o,e=sp.communicate() 6 | if rc==0: 7 | if bool(o)==True: 8 | print(o) 9 | #print(bool(o),bool(e)) 10 | ''' 11 | if bool(o)==False and bool(e)==True: 12 | print(e.splitlines()[0].split()[2].strip("\"")) 13 | ''' 14 | if bool(o)==False: 15 | if bool(e)==True: 16 | print(e.splitlines()[0].split()[2].strip("\"")) 17 | else: 18 | print(e) 19 | -------------------------------------------------------------------------------- /Section 13/3.Document-get-bash-version.py: -------------------------------------------------------------------------------- 1 | import subprocess 2 | cmd=["bash","--version"] 3 | sp=subprocess.Popen(cmd,shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE,universal_newlines=True) 4 | rc=sp.wait() 5 | o,e=sp.communicate() 6 | 7 | if rc==0: 8 | for each_line in o.splitlines(): 9 | if "version" in each_line and "release" in each_line: 10 | print(each_line.split()[3].split('(')[0]) 11 | else: 12 | print("Command was failed and error is: ",e) 13 | -------------------------------------------------------------------------------- /Section 14/1.Document-create-a-file.py: -------------------------------------------------------------------------------- 1 | #Working with text files 2 | ''' 3 | fo=open('newdemo.txt','w') 4 | #print(fo.mode) 5 | #print(fo.readable()) 6 | #print(fo.writable()) 7 | fo.close() 8 | ''' 9 | ''' 10 | my_content=["This is a data -1\n","This is a data-2\n","This is a data-3"] 11 | fo=open("random.txt",'w') 12 | fo.write("This is a first line\n") 13 | fo.write("This is a second line\n") 14 | fo.write("This is a third line") 15 | #fo.writelines(my_content) 16 | fo.close() 17 | ''' 18 | ''' 19 | my_content=['This is using loop-iteratioin-1','This is using loop-iterantion-2','This is using loop-iteratioin-3'] 20 | 21 | fo=open("with_loop.txt",'a') 22 | 23 | for each_line in my_content: 24 | fo.write(each_line+"\n") 25 | fo.close() 26 | ''' 27 | ''' 28 | 29 | fo=open("with_loop.txt","r") 30 | data=fo.read() 31 | fo.close() 32 | 33 | print(data) 34 | ''' 35 | ''' 36 | fo=open("with_loop.txt","r") 37 | print(fo.readline()) 38 | print(fo.readline()) 39 | fo.close() 40 | ''' 41 | 42 | fo=open("with_loop.txt","r") 43 | data=fo.readlines() 44 | fo.close() 45 | ''' 46 | for each in range(3): 47 | print(data[each]) #data[0], data[1],data[2] 48 | ''' 49 | print(data[-1]) 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /Section 14/2.Document-s-d.py: -------------------------------------------------------------------------------- 1 | #sfile="C:\\Users\\Automation\\Desktop\\random.txt" 2 | #dfile="C:\\Users\\Automation\\Downloads\\newrandom.txt" 3 | sfile=input("Enter your source file: ") 4 | dfile=input("Enter your destination file: ") 5 | sfo=open(sfile,'r') 6 | content=sfo.read() 7 | sfo.close() 8 | 9 | dfo=open(dfile,'w') 10 | dfo.write(content) 11 | dfo.close() -------------------------------------------------------------------------------- /Section 15/1.Document-read-csv-file.py: -------------------------------------------------------------------------------- 1 | import csv 2 | req_file="C:\\Users\\Automation\\Desktop\\hi\\new_info.csv" 3 | 4 | fo=open(req_file,"r") 5 | content=csv.reader(fo,delimiter="|") 6 | for each in content: 7 | print(each) 8 | 9 | fo.close() 10 | 11 | -------------------------------------------------------------------------------- /Section 15/2.Document-read-a-header-and-finding-no-of-rows.py: -------------------------------------------------------------------------------- 1 | import csv 2 | req_file="C:\\Users\\Automation\\Desktop\\hi\\new_info.csv" 3 | 4 | fo=open(req_file,"r") 5 | content=csv.reader(fo,delimiter="|") 6 | #print(list(content)) 7 | #print(f'The header is:\n {list(content)[0]}') 8 | #header=next(content) 9 | #print("The header is: ",header) 10 | print("The no of rows are: ",len(list(content))-1) 11 | ''' 12 | for each in content: 13 | print(each) 14 | ''' 15 | fo.close() 16 | 17 | -------------------------------------------------------------------------------- /Section 15/3.Document-create-csv-file.py: -------------------------------------------------------------------------------- 1 | import csv 2 | #req_file="C:\\Users\\Automation\\Desktop\\hi\\new_info.csv" 3 | ''' 4 | fo=open(req_file,'r') 5 | csv_reader=csv.reader(fo,delimiter="|") 6 | for each_row in csv_reader: 7 | print(each_row) 8 | fo.close() 9 | ''' 10 | req_file="C:\\Users\\Automation\\Desktop\\hi\\demo.csv" 11 | fo=open(req_file,'w',newline="") 12 | csv_writer=csv.writer(fo,delimiter=",") 13 | ''' 14 | csv_writer.writerow(['S_No',"Name",'Age']) 15 | csv_writer.writerow([1,"John",23]) 16 | csv_writer.writerow([2,"Cliton",24]) 17 | ''' 18 | my_data=[['S_No',"Name",'Age'],[1,"John",23],[2,"Cliton",24]] 19 | csv_writer.writerows(my_data) 20 | fo.close() 21 | 22 | 23 | -------------------------------------------------------------------------------- /Section 16/working-with-json-files.py: -------------------------------------------------------------------------------- 1 | import json 2 | #Read a json file 3 | ''' 4 | req_file="myjson.json" 5 | 6 | fo=open(req_file,'r') 7 | #print(fo.read()) 8 | print(json.load(fo)) 9 | 10 | fo.close() 11 | ''' 12 | #Write data(dictionary data) into a json file 13 | my_dict={'Name':'Narendra','skills':['Python','shell','yaml','AWS']} 14 | 15 | req_file="myinfo.json" 16 | 17 | fo=open(req_file,'w') 18 | json.dump(my_dict,fo,indent=4) 19 | 20 | fo.close() 21 | -------------------------------------------------------------------------------- /Section 17/1.Document-.working-with-exceptions.py: -------------------------------------------------------------------------------- 1 | ''' 2 | print("Welcome to exceptions concept") 3 | print("Now it is fine") 4 | fo=open("nari.txt") 5 | ''' 6 | 7 | ''' 8 | try: 9 | fo=open("nari.txt") 10 | print(fo.read()) 11 | fo.close() 12 | except Exception as e: 13 | print(e) 14 | ''' 15 | 16 | 17 | my_list=[3,4,5] 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | ''' 30 | 31 | try: 32 | print(my_list[4]) 33 | except Exception as e: 34 | print(e) 35 | ''' 36 | 37 | #print(my_list[4]) 38 | 39 | 40 | #print("This code will also execetues") 41 | 42 | 43 | try: 44 | import fabric 45 | except Exception as e: 46 | print(e) 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /Section 17/2.Document-exception-handling-for-known-exceptions.py: -------------------------------------------------------------------------------- 1 | #NameError 2 | #TypeError 3 | #FileNotFoundError 4 | #ZeroDivisionError 5 | 6 | try: 7 | print("This is try block") 8 | import fabric 9 | print(a) 10 | #print(4+"hi") 11 | #open('asdfas.txt') 12 | #print(5/0) 13 | 14 | except FileNotFoundError: 15 | print("File is not present to open it") 16 | except NameError: 17 | print("Variable is not defined") 18 | except TypeError: 19 | print("Adding number and string is not possible") 20 | except ZeroDivisionError: 21 | print("Division with zero is not possible") 22 | except ModuleNotFoundError: 23 | print("Please install fabric to use it") 24 | except Exception as e: 25 | print(e) 26 | finally: 27 | print("Finally this will executes") 28 | 29 | -------------------------------------------------------------------------------- /Section 17/3.Document-differce-finally-esle.py: -------------------------------------------------------------------------------- 1 | try: 2 | a=9 3 | print(a) 4 | except NameError: 5 | print("Variable is not defined") 6 | except Exception as e: 7 | print("Exception occured:",e) 8 | else: 9 | print("This will execute if there is no exceptions in try block") 10 | finally: 11 | print("This will executes always") 12 | -------------------------------------------------------------------------------- /Section 17/4.Document-custom-exceptions.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 3 | age=23 4 | 5 | 6 | if age>30: 7 | print("Valid age") 8 | else: 9 | raise ValueError("Age is less than 30") 10 | 11 | ''' 12 | age=20 13 | 14 | try: 15 | assert age>30 16 | print("Valid age") 17 | except AssertionError: 18 | print("Raised with assert because age is lessthan 30") 19 | except: 20 | print("Exception occured") 21 | 22 | -------------------------------------------------------------------------------- /Section 18/1.Document-run-your-commands.py: -------------------------------------------------------------------------------- 1 | import os 2 | import time 3 | import platform 4 | def mycode(cmd1,cmd2): 5 | print("Please wait. Cleaning the screen....") 6 | time.sleep(2) 7 | os.system(cmd1) 8 | print("Please wait finding the list of dir and files") 9 | time.sleep(2) 10 | os.system(cmd2) 11 | if platform.system()=="Windows": 12 | mycode("cls","dir") 13 | else: 14 | mycode('clear','ls -lrt') -------------------------------------------------------------------------------- /Section 18/10.variable-leng-keyword.py: -------------------------------------------------------------------------------- 1 | def display(p,**karg): 2 | print(p) 3 | print(karg) 4 | return None 5 | #display(4,5) 6 | #display(b=5,a=4) 7 | #display(a=4,b=5,c=6) 8 | display(56,x=5,y="Hi",z=6.7,user="root") -------------------------------------------------------------------------------- /Section 18/12.Document-change-working-dir.py: -------------------------------------------------------------------------------- 1 | #!/usr/local/bin/python3 2 | import os 3 | ''' 4 | req_path=input("Enter path to change working dir: ") 5 | print("The current working dir is: ",os.getcwd()) 6 | try: 7 | os.chdir(req_path) 8 | print("Now your new working dir is: ",os.getcwd()) 9 | except FileNotFoundError: 10 | print("Given path is not a valid path. So cant change working directory") 11 | except NotADirectoryError: 12 | print("Given path is a file path. So cant change working directory") 13 | except PermissionError: 14 | print("Sorry you dont have access for the given path. So cant chagne working directory") 15 | except Exception as e: 16 | print(e) 17 | ''' 18 | 19 | def main(): 20 | req_path=input("Enter path to change working dir: ") 21 | print("The current working dir is: ",os.getcwd()) 22 | try: 23 | os.chdir(req_path) 24 | print("Now your new working dir is: ",os.getcwd()) 25 | except FileNotFoundError: 26 | print("Given path is not a valid path. So cant change working directory") 27 | except NotADirectoryError: 28 | print("Given path is a file path. So cant change working directory") 29 | except PermissionError: 30 | print("Sorry you dont have access for the given path. So cant chagne working directory") 31 | except Exception as e: 32 | print(e) 33 | return None 34 | 35 | 36 | if __name__=="__main__": 37 | main() 38 | -------------------------------------------------------------------------------- /Section 18/2.Document-defining-fun.py: -------------------------------------------------------------------------------- 1 | def display(): 2 | print("Welcome to functions concept") 3 | print("Simple way to define your function") 4 | return None 5 | 6 | display() 7 | 8 | 9 | print(len("hi")) 10 | x=40 11 | print(id(x)) 12 | 13 | 14 | #Rules to define function name: 15 | #Function name should have only a-z,A-Z,0-9, _ 16 | #Function shuold not start with number but can it be start with _ 17 | #Dont include any space. 18 | #Function must be define befor calling it 19 | 20 | 21 | x=(5,6) 22 | print(len(x)) 23 | 24 | print(min(x)) 25 | print(max(x)) 26 | 27 | 28 | 29 | x="5" 30 | print(int(x)) -------------------------------------------------------------------------------- /Section 18/3.Documnet-converting-into-fun.py.py: -------------------------------------------------------------------------------- 1 | def welcome_msg(): 2 | print("Welcome to Python Scripting") 3 | print("Python is easy to learn") 4 | return None 5 | def known_concepts(): 6 | print("Now we are good with bascis") 7 | print("We are about to start functions concepts in python") 8 | return None 9 | def learning_concepts(): 10 | print("Function are very easy in python") 11 | print("Now we are writing simple functions") 12 | return None 13 | welcome_msg() 14 | known_concepts() 15 | learning_concepts() -------------------------------------------------------------------------------- /Section 18/4.Document-scope-of-the-variables.py: -------------------------------------------------------------------------------- 1 | def myfunction1(): 2 | x=60 #This is local variable 3 | print("Welcome to functions") 4 | print("x value from fun1: ",x) 5 | #myfunction2() 6 | return None 7 | 8 | 9 | def myfunction2(y): #Parameter 10 | print("Thank you!!") 11 | print("x value from fun2: ",y) 12 | return None 13 | 14 | def main(): 15 | #global x 16 | x=10 17 | myfunction1() 18 | myfunction2(x) #Argument 19 | return None 20 | 21 | 22 | main() 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /Section 18/5.Document-function-with-simple-arguments.py: -------------------------------------------------------------------------------- 1 | ''' 2 | def get_result(value): #parameters/positional arguments 3 | result=value+10 4 | print(f'Your result is: {result}') 5 | return None 6 | def main(): 7 | #global num 8 | num=eval(input("Enter your number: ")) 9 | get_result(num) #Arguments 10 | return None 11 | 12 | main() 13 | ''' 14 | def get_add(p,q): 15 | aresult=p+q 16 | print(f'The addition of {p} and {q} is: {aresult}') 17 | return None 18 | def get_sub(m,n): 19 | sresult=m-n 20 | print(f'The sub of {m} and {n} is: {sresult}') 21 | return None 22 | 23 | def main(): 24 | a=eval(input("Enter your first num: ")) 25 | b=eval(input("Enter your second num: ")) 26 | get_add(a,b) 27 | get_sub(a,b) 28 | #x=50 29 | #get_sub(19,x) 30 | return None 31 | 32 | main() 33 | -------------------------------------------------------------------------------- /Section 18/6.Document-fun-with-arg-return-values.py: -------------------------------------------------------------------------------- 1 | ''' 2 | def get_addition(a,b): 3 | result=a+b 4 | #print(f"The addition of {a} and {b} is: {result}") 5 | return result 6 | def main(): 7 | a=eval(input("Enter your first number: ")) 8 | b=eval(input("Enter your second number :")) 9 | result=get_addition(a,b) 10 | print(f"The addition of {a} and {b} is: {result}") 11 | return None 12 | main() 13 | ''' 14 | 15 | def multiply_num_10(value): 16 | #result=value*10 17 | #return result 18 | return value*10 19 | 20 | 21 | def main(): 22 | num=eval(input("Enter your number: ")) 23 | result=multiply_num_10(num) 24 | print("The result is: ",result) 25 | 26 | 27 | 28 | 29 | main() -------------------------------------------------------------------------------- /Section 18/7.Document-fun-with-default-arguments.py: -------------------------------------------------------------------------------- 1 | ''' 2 | def display(a=1): 3 | print("The value of a is: ",a) 4 | return None 5 | 6 | display(4) 7 | display(5) 8 | display() 9 | ''' 10 | 11 | ''' 12 | def add_numbers(a,b=0): 13 | result=a+b 14 | print("The result is: ",result) 15 | return None 16 | add_numbers(4,5) 17 | add_numbers(5) 18 | add_numbers(7) 19 | ''' 20 | 21 | def working_on_some(user="root"): 22 | print(f"working with {user}") 23 | return None 24 | 25 | working_on_some("weblogic_admin") -------------------------------------------------------------------------------- /Section 18/8.Document-function-with-keyword-based-arguments.py: -------------------------------------------------------------------------------- 1 | def display(a,b): 2 | print(f'a={a}') 3 | return None 4 | 5 | display(3,4) 6 | display(a=3,b=4) 7 | display(b=4,a=3) -------------------------------------------------------------------------------- /Section 18/9.Document-functions-with-variable-length-argument.py: -------------------------------------------------------------------------------- 1 | def display(*arg): 2 | for each in arg: 3 | print(type(each)) 4 | return None 5 | #display() 6 | #display(4) 7 | display(4,5,67) 8 | print('-------------') 9 | display("hi",4.65) -------------------------------------------------------------------------------- /Section 19/2.Document-0regexe-pat-rules-creation.py: -------------------------------------------------------------------------------- 1 | import re 2 | text="This . is a python and it is easy to learn and it is popular one for dev and automation" 3 | ''' 4 | my_pat= 'i[ston]' #is,it,io,in 5 | #print(len(re.findall(my_pat,text))) 6 | print(re.findall(my_pat,text)) 7 | 8 | ''' 9 | 10 | 11 | #my_pat="x[abcdeflmnopq]y" ==> xay,xby.....xqy 12 | # ="x[a-fl-q]y" 13 | ''' 14 | my_pat='\.' 15 | print(re.findall(my_pat,text)) 16 | ''' 17 | ''' 18 | text="This is a ip address of my db1 server: 255.255.255.255 2456234512341234" 19 | 20 | my_pat="\d\d\d\.\d\d\d\.\d\d\d\.\d\d\d" 21 | print(re.findall(my_pat,text)) 22 | ''' 23 | 24 | 25 | ''' 26 | text="This is python @ 345 _ - (" 27 | print(re.findall('\w',text)) 28 | #print(re.findall('.',text)) 29 | print(re.findall("\W",text)) 30 | ''' 31 | 32 | 33 | text="456 90 this is about deciaml re98gex" 34 | print(re.findall('\d\d',text)) -------------------------------------------------------------------------------- /Section 19/3.Document-rules-2.py: -------------------------------------------------------------------------------- 1 | import re 2 | text='isa python l earn and \n itis easy to' 3 | #my_pat='^i[ts]' 4 | #my_pat="learn$" 5 | #my_pat=r"\blearn\b" 6 | #my_pat=r"\Blearn\B" 7 | my_pat=r"\n" 8 | print(re.findall(my_pat,text)) -------------------------------------------------------------------------------- /Section 19/4.Document-rules-3.py: -------------------------------------------------------------------------------- 1 | import re 2 | ''' 3 | text="This is a pythonnnn and python aaa haaaafd xyzaaaaaaaa" 4 | #my_pat=r'\bpython{4}\b' 5 | my_pat=r'\bxyza{8}\b' 6 | print(re.findall(my_pat,text)) 7 | ''' 8 | text="xaz asdfa sdf xaaz xaaaaaaaz xaaaaz xz" 9 | #my_pat=r'\bxa{2,}z\b' 10 | #my_pat=r'xa{1,}z' 11 | #my_pat=r'xa*z' 12 | my_pat=r'xa?z' 13 | print(re.findall(my_pat,text)) -------------------------------------------------------------------------------- /Section 19/5.Document-regex-flags.py: -------------------------------------------------------------------------------- 1 | import re 2 | ''' 3 | text="this is a string ThIs is a new staring THIS" 4 | my_pat=r'this' 5 | print(re.findall(my_pat,text,re.I)) 6 | ''' 7 | text="""this is a string EnD 8 | this is second line enD 9 | This is third line end 10 | asfasd this end""" 11 | #print(text) 12 | 13 | #my_pat=r'^this' 14 | my_pat=r'end$' 15 | 16 | print(re.findall(my_pat,text,re.M|re.I)) -------------------------------------------------------------------------------- /Section 19/6.Document-search-and-match-practice.py: -------------------------------------------------------------------------------- 1 | import re 2 | text="""This is for 3 | python2 and there are two major 4 | vers python3 and python in future python4""" 5 | 6 | pat=r'\bpython[23]?\b' 7 | ''' 8 | #print(re.findall(pat,text)) 9 | match_ob=re.search(pat,text) 10 | #rint(match_ob) 11 | if match_ob: 12 | print("match from ur pattern: ",match_ob.group()) 13 | print('Starting index: ',match_ob.start()) 14 | print('Ending index: ',match_ob.end()-1) 15 | print("Length: ",match_ob.end()-match_ob.start()) 16 | else: 17 | print("No match found") 18 | ''' 19 | text="""PYTHON2 and there are two major 20 | vers python3 and python in future python4""" 21 | 22 | pat=r'\bpython[23]?\b' 23 | match_ob=re.match(pat,text,re.I) 24 | if match_ob: 25 | print("match from ur pattern: ",match_ob.group()) 26 | print('Starting index: ',match_ob.start()) 27 | print('Ending index: ',match_ob.end()-1) 28 | print("Length: ",match_ob.end()-match_ob.start()) 29 | else: 30 | print("No match found") 31 | 32 | -------------------------------------------------------------------------------- /Section 19/7.Document-find-all-find-iter.py: -------------------------------------------------------------------------------- 1 | import re 2 | my_str="This is python and we are having python2 and python3 version" 3 | my_pat=r'\bpython[23]?\b' 4 | #print(re.search(my_pat,my_str)) 5 | #print(len(re.findall(my_pat,my_str))) 6 | #print(re.findall(my_pat,my_str)) 7 | 8 | for each_ob in re.finditer(my_pat,my_str): 9 | print(f'The match is: {each_ob.group()} starting index: {each_ob.start()}, ending index {each_ob.end()-1}') -------------------------------------------------------------------------------- /Section 19/9.Document-complie-operations.py: -------------------------------------------------------------------------------- 1 | import re 2 | my_str="This is about python. Python is easy to learn and we have two major versions: python2 and python3 " 3 | 4 | my_pat=r'\bPython[23]?\b' 5 | 6 | #print(re.search(my_pat,my_str)) 7 | #print(re.findall(my_pat,my_str,flags=re.I)) 8 | #print(re.split(my_pat,my_str)) 9 | 10 | 11 | pat_ob=re.compile(my_pat,flags=re.I) 12 | print(pat_ob) 13 | print(pat_ob.search(my_str)) 14 | print(pat_ob.findall(my_str)) 15 | 16 | 17 | #re.findall(my_pat,my_str)===> re.complie(my_pat).findall(my_str) 18 | 19 | -------------------------------------------------------------------------------- /Section 20/1.Document-working-with-remote-linux-from-windows.py: -------------------------------------------------------------------------------- 1 | #!/bin/python 2 | import paramiko 3 | ssh = paramiko.SSHClient() 4 | ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 5 | #ssh.connect(hostname='3.92.79.119',username='ec2-user',password='paramiko123',port=22) 6 | ssh.connect(hostname='3.92.79.119',username='ec2-user',key_filename='/home/Automation/.ssh/id_rsa',port=22) 7 | #stdin, stdout, stderr = ssh.exec_command('whoami') 8 | #stdin, stdout, stderr = ssh.exec_command('uptime') 9 | stdin, stdout, stderr = ssh.exec_command('free -m') 10 | print("The output is: ") 11 | print(stdout.readlines()) 12 | 13 | 14 | print("THe error is: ") 15 | print(stderr.readlines()) 16 | -------------------------------------------------------------------------------- /Section 20/2.Document-transfer_files.py: -------------------------------------------------------------------------------- 1 | import paramiko 2 | ssh = paramiko.SSHClient() 3 | ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 4 | ssh.connect(hostname='54.165.97.91',username='ec2-user',password='paramiko123',port=22) 5 | sftp_client=ssh.open_sftp() 6 | 7 | #sftp_client.get('/home/ec2-user/paramiko_download.txt','paramiko_downloaded_file.txt') 8 | #sftp_client.chdir("/home/ec2-user") 9 | #print(sftp_client.getcwd()) 10 | #sftp_client.get('demo.txt','C:\\Users\\Automation\\Desktop\\download_file.txt') 11 | sftp_client.put("transfer_files.py",'/home/ec2-user/transfer_files.py') 12 | sftp_client.close() 13 | ssh.close() -------------------------------------------------------------------------------- /Section 21/shutil-part-1.py: -------------------------------------------------------------------------------- 1 | #!/usr/local/bin/python3 2 | import shutil 3 | #copy', 'copy2', 'copyfile', 'copyfileobj', 'copymode', 'copystat', 'copytree' 4 | 5 | #copyfile-->copy --> copy2 6 | #src="/home/Automation/working_with_remote_server.py" 7 | src="/home/Automation/shutil_part_1.py" 8 | dest="/home/Automation/working_with_remote_server.py_bkp" 9 | #shutil.copyfile(src,dest) 10 | #shutil.copy(src,dest) #same permissions for src and dest 11 | #shutil.copy2(src,dest) #same meta data for dest as well 12 | #shutil.copymode(src,dest) 13 | #shutil.copystat(src,dest) 14 | 15 | #f1=open('xyz.txt','r') 16 | #f2=open('pqr.txt','w') 17 | #shutil.copyfileobj(f1,f2) 18 | 19 | #src="/home/Automation/tomcat7" 20 | #shutil.copytree(src,'/tmp/tomcat') 21 | 22 | shutil.rmtree('/tmp/tomcat') -------------------------------------------------------------------------------- /Section 22/1.Document-introduction_to_oops.py: -------------------------------------------------------------------------------- 1 | import os 2 | class Tomcat: 3 | def get_details_for_each_tomcat(self,server_xml): 4 | self.tcf=server_xml 5 | self.th=os.path.dirname(os.path.dirname(server_xml)) 6 | return None 7 | 8 | def display_details(self): 9 | print(f'The tomcat config file is: {self.tcf}\nThe tomcat home is: {self.th}') 10 | return None 11 | 12 | def main(): 13 | tomcat7=Tomcat() 14 | tomcat9=Tomcat() 15 | 16 | tomcat7.get_details_for_each_tomcat("/home/Automation/tomcat7/conf/server.xml") 17 | #get_details_for_each_tomcat('tomcat7',"/home/Automation/tomcat7/conf/server.xml") 18 | tomcat9.get_details_for_each_tomcat("/home/Automation/tomcat9/conf/server.xml") 19 | #get_details_for_each_tomcat('tomcat9',"/home/Automation/tomcat9/conf/server.xml") 20 | #print(tomcat9.tcf) 21 | #print(tomcat7.th) 22 | #print(tomcat9.th) 23 | #print(tomcat7.tcf) 24 | tomcat9.display_details() 25 | tomcat7.display_details() 26 | #display_details('tomcat7') 27 | tomcat9.display_details() 28 | 29 | return None 30 | 31 | if __name__=="__main__": 32 | main() 33 | -------------------------------------------------------------------------------- /Section 22/2.Document-working_on_attributes.py: -------------------------------------------------------------------------------- 1 | class emp: 2 | count=0 3 | def get_name_age_salary(self,name,age,salary): 4 | self.name=name 5 | self.age=age 6 | self.salary=salary 7 | self.increase_count_for_emp() 8 | #self.display_details() 9 | return None 10 | def increase_count_for_emp(self): 11 | emp.count=emp.count+1 12 | return None 13 | def display_details(self): 14 | print(f'The name is: {self.name}\nThe age is: {self.age}\nThe salary is: {self.salary}') 15 | return None 16 | 17 | emp1=emp() 18 | emp2=emp() 19 | 20 | emp1.get_name_age_salary('John',34,45000) 21 | #emp1.increase_count_for_emp() 22 | emp2.get_name_age_salary('Cliton',25,54000) 23 | #emp2.increase_count_for_emp() 24 | 25 | print(emp.count) 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /Section 22/3.Document-using_init_method.py: -------------------------------------------------------------------------------- 1 | class Emp(object): 2 | def __init__(self,name,salary): 3 | self.name=name 4 | self.salary=salary 5 | return None 6 | def display(self): 7 | print(f"The name is: {self.name}\nThe salary is: {self.salary}") 8 | return None 9 | 10 | 11 | emp1=Emp('Ramu',56000) 12 | emp2=Emp("Naren",90000) 13 | 14 | emp1.display() 15 | #emp2.display() -------------------------------------------------------------------------------- /Section 22/4.1.Document-without_oops.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | import os 3 | 4 | def get_all_tomcats(): 5 | list_of_config_files=[] 6 | for r,d,f in os.walk("/"): 7 | for each_file in f: 8 | if each_file=='server.xml': 9 | list_of_config_files.append(os.path.join(r,each_file)) 10 | return list_of_config_files 11 | def display_details(home_cnf_files): 12 | for each_key in home_cnf_files.keys(): 13 | print(f'The Tomcat home is: {home_cnf_files[each_key][0]}') 14 | print(f'The Tomcat config file is:{home_cnf_files[each_key][1]}' ) 15 | return None 16 | 17 | def main(): 18 | print("Finding list of tomcats...") 19 | list_of_tomcats=get_all_tomcats() 20 | #print(list_of_tomcats) 21 | cnt=1 22 | home_cnf_files={} 23 | for each_config_file in list_of_tomcats: 24 | t_home=os.path.dirname(os.path.dirname(each_config_file)) 25 | t_cnf_file=each_config_file 26 | home_cnf_files['tomcat'+str(cnt)]=[t_home,t_cnf_file] 27 | cnt+=1 28 | #print(home_cnf_files) 29 | display_details(home_cnf_files) 30 | return None 31 | 32 | 33 | if __name__ == '__main__': 34 | main() 35 | -------------------------------------------------------------------------------- /Section 22/4.2.Document-working_with_oops.py: -------------------------------------------------------------------------------- 1 | class emp: 2 | count=1 3 | 4 | 5 | emp.count=emp.count+1 6 | print(emp.count) -------------------------------------------------------------------------------- /Section 22/5.Document-constructor_and_destructor_of_an_object.py: -------------------------------------------------------------------------------- 1 | class Person(object): 2 | def __init__(self,name,age): 3 | print("an object has been created") 4 | self.name=name 5 | self.age=age 6 | return None 7 | def __del__(self): 8 | print("object has been deleted") 9 | return None 10 | 11 | 12 | per1=Person('Jhon',26) 13 | 14 | 15 | -------------------------------------------------------------------------------- /Section 22/6.1.Document-polymorphism.py: -------------------------------------------------------------------------------- 1 | class Tomcat(object): 2 | def __init__(self,home,ver): 3 | self.home=home 4 | self.version=ver 5 | return None 6 | def display(self): 7 | print("This is from tocmat class") 8 | print(self.home) 9 | print(self.version) 10 | return None 11 | class Apache(object): 12 | def __init__(self,home,ver): 13 | self.home=home 14 | self.version=ver 15 | return None 16 | def display(self): 17 | print("This is from apache class") 18 | print(self.home) 19 | print(self.version) 20 | return None 21 | 22 | tom_ob=Tomcat('/home/tomcat9','7.6') 23 | apa_ob=Apache("/etc/httpd",'2.4') 24 | 25 | tom_ob.display() 26 | apa_ob.display() -------------------------------------------------------------------------------- /Section 22/6.2.Document-inheritance.py: -------------------------------------------------------------------------------- 1 | class Tomcat(object): 2 | def __init__(self,home,ver): 3 | self.home=home 4 | self.version=ver 5 | return None 6 | def display(self): 7 | print(self.home) 8 | print(self.version) 9 | return None 10 | class Apache(Tomcat): 11 | def __init__(self,home,ver): 12 | self.home=home 13 | self.version=ver 14 | return None 15 | tom_ob=Tomcat('/home/tomcat9','7.6') 16 | apa_ob=Apache("/etc/httpd",'2.4') 17 | 18 | 19 | tom_ob.display() 20 | apa_ob.display() -------------------------------------------------------------------------------- /Section 22/7.Document-Encpasulation.py: -------------------------------------------------------------------------------- 1 | class Person(object): 2 | def assing_name_and_age(self,name,age): 3 | self.name=name 4 | self.__age=age 5 | self.__display() 6 | return None 7 | def __display(self): 8 | print(self.name,self.__age) 9 | return None 10 | 11 | per1=Person() 12 | per1.assing_name_and_age('John',32) 13 | 14 | #per1.__display() 15 | #print(per1.name) 16 | #print(per1.__age) --------------------------------------------------------------------------------