User Tools

Site Tools


scripting:python

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
scripting:python [2023/08/09 16:01] jotasandokuscripting:python [2024/12/23 13:46] (current) – S jotasandoku
Line 1: Line 1:
 **__PYTHON__**\\ **__PYTHON__**\\
-\\+ 
 + 
 +== FOLLOW PYTHON CODE (WIP) === 
 + 
 +This is just covering the simple case of an installed python program which is invoked via interactive cli.\\ 
 +I take [[https://github.com/ipspace/netlab]] installed in a virtual environment in Ubuntu.\\ 
 + 
 +The executable archive for the main command (argv[0]) must be present in a location contained in 'PATH'. For example  ''./bin/netlab''. This is what the executable looks like: 
 + 
 +  #!/home/jaime/netsim-labs/bin/python3 
 +  import netsim 
 +  import netsim.cli 
 +  netsim.cli.lab_commands(__file__) 
 + 
 +''netsim'' and ''cli'' are a folder and subfolder under ''./lib/python3.12/site-packages/''. The folders are ''packages'' because, together with a lot of .py files, we have the file ''__init__.py''. It contains common logic 
 + 
 +  * Inside netsim/cli/__init__.py: 
 +    * we have the function ''lab_commands''. Note this function is invoked from the main executable ''netlab'' 
 +    * the standard module ''argparse'' which is a library for common management of interactive cli. See tutorials like  [[https://www.youtube.com/watch?v=aGy7U5ItLRk|this]] 
 + 
 +---- 
 **Python virtual environment**: Isolated "environments" where specific versions of Python can be installed along with independent sets of libraries and dependencies. **Python virtual environment**: Isolated "environments" where specific versions of Python can be installed along with independent sets of libraries and dependencies.
 \\ \\
Line 138: Line 159:
 ---- ----
  
-__**REGEX**__ +__**REGEX IN PYTHON**__
-\\+
   * [[https://regex101.com/]]   * [[https://regex101.com/]]
   * [[https://github.com/networktocode/ntc-templates|TextFSM]]   * [[https://github.com/networktocode/ntc-templates|TextFSM]]
-  * ALL INFO [[https://community.cisco.com/t5/controllers/python-netmiko-how-to-print-out-specific-line-matches-with-cisco/td-p/4069348|HERE] +  * regex search ways in python: MATCH, SEARCH, FINDALL, and SUB  
-  * All regex can be done with or without [[https://www.stat.berkeley.edu/~spector/extension/python/notes/node79.html|compiling]] but is more efficient. + 
-Resources  [[https://docs.python.org/2/library/re.html|here1]] and  [[http://www.pythonlearn.com/html-007/cfbook012.html|here2]]\\ +**__SEARCH__**
-https://panda314159.net/doku.php?id=scripting:python_scripts:regex1.py+
 \\ \\
-regex search ways in python: MATCHSEARCH, FINDALL, and SUB \\+A found 'yes or no'. Returns a Match object if there is a match anywhere in the string 
 + 
 +  txt = "The rain in Spain" 
 +  x = re.search("^The.*Spain$"txt)  
 + 
 +More ellaborated:  
 + 
 +  name_regex = re.compile(r"^vrf\s+(?P<name>\S+)"
 +  name_match = name_regex.search(vrf) 
 +  sub_dict = {} 
 +  vrf_dict = {name_match.group("name"): sub_dict} 
 +         
 \\ \\
-**FINDALL:** Finds all instances of the matched string. All the occurrences go inside a LIST. findall() matches all occurrences of a pattern, not just the first one. We can also use ''compile'' 
  
-  re.findall(   'pattern', 'did you find one pattern or many patterns'+**FINDALL:** Finds all instances of the matched string. All the occurrences go inside a LIST.  
 + 
 +  res_list1 = re.findall('pattern', 'did you find one pattern or many patterns'
   ['pattern', 'pattern']   ['pattern', 'pattern']
  
-Example: find any serial number 8 characters long after the pattern: "Caller pc   :0x": 
-  file = fileh.read() 
-  serials = re.findall(r'Caller pc    :0x([a-zA-Z0-9]{8}\s' , file) 
 \\ \\
 **SUB:** Can replace a parameter.\\ **SUB:** Can replace a parameter.\\
Line 163: Line 192:
   'did you find one turnip or many turnips'   'did you find one turnip or many turnips'
  
-**SEARCH:**\\ +
-  name_regex = re.compile(r"^vrf\s+(?P<name>\S+)"+
-  name_match = name_regex.search(vrf) +
-  sub_dict = {} +
-  vrf_dict = {name_match.group("name"): sub_dict} +
-         +
-\\+
 **MATCH**: **MATCH**:
   - Compile the expressions   - Compile the expressions
Line 233: Line 256:
        
      
-To **show the current folder path** and open a file in it+To **show the current folder path** and open a file in it. own directory / own folder.
  
   import os   import os
Line 307: Line 330:
   """)   """)
 \\ \\
-Slicing lists\\ +== SLICING === 
-  print namelist[:2]   prints up to but not including index 2. So and 1.+ 
 +  # [:2] - First 2 elements 
 +  print("[:2] ->",  x[:2])  [0, 1] 
 + 
 +  # [2:] - Everything from index 2 onwards 
 +  print("[2:] ->", x[2:])  # [2, 3, 4, 5, 6, 7, 8, 9] 
 + 
 +  # [-2:] - Last 2 elements 
 +  print("[-2:] ->", x[-2:])  # [8, 9] 
 + 
 +  # [:-2] - Everything EXCEPT last 2 elements 
 +  print("[:-2] ->", x[:-2])  # [01, 2, 3, 4, 5, 6, 7] 
 + 
 + 
 + 
 \\ \\
 Updating list Updating list
Line 637: Line 675:
 Many cloud api responses are just a dictionary with a **key named data** and then a big element structure which is a **list of dictionaries**. \\ Many cloud api responses are just a dictionary with a **key named data** and then a big element structure which is a **list of dictionaries**. \\
 To start accessing the data we do ''resources = data["resources"]'' so now resources is a big list and we can use for/if and things like ''end_result.append(res_elements["instances"][0]["attributes"]["network_security_group_id"])'' to access element in the structure. To start accessing the data we do ''resources = data["resources"]'' so now resources is a big list and we can use for/if and things like ''end_result.append(res_elements["instances"][0]["attributes"]["network_security_group_id"])'' to access element in the structure.
-More info here : [[https://gitlab.mycompany2datacloud.com/jaime.santos.amandi/python-netops/-/blob/master/classes/count.py]] 
 \\ \\
  
Line 644: Line 681:
 BELOW **typical work path**:  BELOW **typical work path**: 
   - Convert API response to json   - Convert API response to json
-  - Store json data into a file+  - Store json data into a file (not pretty)
   - Retrieve the file into dict format to work on it   - Retrieve the file into dict format to work on it
  
  
-  #!/usr/bin/python3.6 +
-  import requests +
-  import json +
-   +
-  # BETTER THIS TO BE FILE 1 +
-  region = "&region=uk-london-1" +
-   +
-  url = "https://folsom.mycompany2datacloud.com/folsom/instance?compartment_id=ocid1.compartment.oc1..  aaaaaaaalnhfd3hp5clfkbn2wjj3h3gysjct6fjtzbc7c5lvjdfs62gjtllq" + region +
-  payload = {} +
-  headers = { +
-          'Authorization': 'Bearer zzzzzzzzzzz' +
-  } +
-  response = requests.get(url, headers=headers, data=payload) +
-  +
   # Convert the api response to dictionary and store it   # Convert the api response to dictionary and store it
   json_data = response.json()   json_data = response.json()
   with open("backend_results.json", "w") as fp:   with open("backend_results.json", "w") as fp:
       json.dump(json_data,fp)        json.dump(json_data,fp) 
 +  !
 +  with open("backend_results.json", "r") as fp:
 +      json.dump(fp) 
  
 POST method. More info [[https://www.geeksforgeeks.org/get-post-requests-using-python/|here]] POST method. More info [[https://www.geeksforgeeks.org/get-post-requests-using-python/|here]]
Line 809: Line 836:
  
 ---- ----
-NGROK:\\+NGROK: 
 +\\
  
   *     Demoing web sites without deploying   *     Demoing web sites without deploying
Line 825: Line 853:
 __CODING NOTES__ __CODING NOTES__
   * [[https://app.coderpad.io/dashboard/questions/examples/]]   * [[https://app.coderpad.io/dashboard/questions/examples/]]
-  * Use a 'list of unchecked cells''... At the end, the index of the only unchecked cell will be the missing page number.+  * Use a ''list of unchecked cells''... At the end, the index of the only unchecked cell will be the missing page number.
  
     pages_qty = len(page_numbers) + 1     pages_qty = len(page_numbers) + 1
Line 832: Line 860:
  
  
 +
 +----
 +TIME COMPLEXITY:
 +\\
 +[[https://towardsdatascience.com/understanding-time-complexity-with-python-examples-2bda6e8158a7]]
 +\\
 +  * Best case O(1) ; Worst case: O(n!)
  
 ---- ----
Line 841: Line 876:
   * Moving-window average algorithm   * Moving-window average algorithm
   * Sorted lists of numbers   * Sorted lists of numbers
 +
 +
scripting/python.1691596918.txt.gz · Last modified: (external edit)