devwiki:python

Differences

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

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
devwiki:python [2023/03/23 07:39] – [file operation] yingdevwiki:python [2024/03/25 06:36] (current) – [Python and interaction with other API] ying
Line 1: Line 1:
  
 +
 +====== Modern Python Practice ======
 +
 +  * nowaday, now one use python 2.x anymore, use python 3 standard, use this
 +    * use pathlib instead of os.path
 +    * use f"{keyword}" instead of "{0}".format(keyword), unless it is easier
 +
 +
 +====== Online Python run ======
 +
 +  * https://jupyter.org/try-jupyter/retro/notebooks/?path=notebooks/Intro.ipynb
 +  * to install locally: <code>pip3 install --upgrade pip</code>
  
 ====== Install related ====== ====== Install related ======
Line 12: Line 24:
     - if you already install XCode (the developer suite for mac), then no need; if not, you can just install the smaller "Command line tools" with your Apple account     - if you already install XCode (the developer suite for mac), then no need; if not, you can just install the smaller "Command line tools" with your Apple account
     - go Apple developer downloads page, search command line tools for xcode, download that and install     - go Apple developer downloads page, search command line tools for xcode, download that and install
 +
 +===== Manage and handle multiple versions of python case =====
 +
 +Situation:
 +  * sometimes, you may have to keep both python 2.7, python 3.x
 +  * and sometimes you want to try python with AI, and AI need to install tons of AI related python modules
 +  * sometimes you just to keep python module in the min form to test something
 +
 +Solution:
 +  * for those case, when install python, never add python to system path
 +  * just download and make python folder a portable folder (you can install and copy the python whole folder to other machine as a portable app, better zip to copy, faster)
 +  * then your computer cmd never know where is python and won't random get your python from somewhere
 +  * then, dynamically set python into python in cmd session or batch file, or use full path to python.exe to run your script
 +    * session based method (win as example) <code dos>SET PATH=D:\App\Python;D:\App_Dev\PortableGit\bin;%PATH%</code>
 +    * batch file method <code dos test.batch>
 +@echo off
 +SetLocal EnableDelayedExpansion
 +set CustPython=D:\App\Python\
 +call !CustPython!python.exe my_script.py
 +</code>
  
  
Line 136: Line 168:
   * get class name <code python>self.__class__.__name__</code>   * get class name <code python>self.__class__.__name__</code>
   * get basename of folder and file <code python>os.path.basename(os.path.normpath('/folderA/folderB/folderC/folderD/')) # 'folderD'</code>   * get basename of folder and file <code python>os.path.basename(os.path.normpath('/folderA/folderB/folderC/folderD/')) # 'folderD'</code>
 +  * get file name without extension <code python>
 +file_name = os.path.basename(file_path).rsplit('.',1)[0]
 +import pathlib
 +file_name_2 = pathlib.Path(file_path).stem
 +</code>
   * get expanded and un-symbolic path <code python>   * get expanded and un-symbolic path <code python>
 os.path.abspath(__file__) os.path.abspath(__file__)
Line 907: Line 944:
 except OSError: except OSError:
     pass     pass
 +    
 +# method 3: all in one check and create if needed, like method 2 but not need try and except since it will be ok for exist
 +os.makedirs(os.path.dirname(output_path), exist_ok=True)
 </code> </code>
   * write python data<code python>   * write python data<code python>
Line 978: Line 1018:
 REM make sure that wheel is in 32/64bit matching your python 32/64bit version REM make sure that wheel is in 32/64bit matching your python 32/64bit version
 pip install C:/some-dir/some-file.whl pip install C:/some-dir/some-file.whl
 +</code>
 +  * How to install extra module into seperate directory <code>
 +python.exe -m pip install --target=D:\my_path\plot_lib matplotlib
 </code> </code>
   * How to install extra modules manually   * How to install extra modules manually
Line 1322: Line 1365:
 result.text # is html in unicode text result.text # is html in unicode text
 </code> </code>
 +  * disable non secure cert warning <code python>requests.packages.urllib3.disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning)</code>
 ===== PIL and Pillow===== ===== PIL and Pillow=====
  
Line 2337: Line 2380:
         send_button.click()         send_button.click()
 </code> </code>
 +
 +====== Python and interaction with other API ======
 +
 +Telegram
 +  - search @BotFather on telegram
 +    * manual: https://core.telegram.org/bots/api
 +  - in the chat, type /newbot, then type your bot "botname", then type your bot "botusername_bot"
 +  - now, your bot api key will show up, copy and save it
 +  - now search your bot "botusername_bot" to start chat with it
 +  - in python, use requests to get the chat from the bot, try one more time if no result <code python>
 +import requests
 +the_key = "api_key"
 +url = "https://api.telegram.org/bot{0}/getUpdates".format(the_key)
 +response = requests.get(url)
 +result = response.json()
 +print(result)
 +</code>
 +  - once you got result in json, you will find the chat id. <code python>result['result']
 +# the list of all chat spec your bot received, yours is likely the first one.
 +my_chat_info = result['result']
 +my_msg_info = my_chat_info[0]['message']
 +# it got info of: chat, date, from, message_id, text
 +my_chat_id = my_msg_info['chat']['id']
 +</code>
 +  - to send a text to that chat from your bot side <code python>
 +reply_text = 'hello world'
 +url = "https://api.telegram.org/bot{key}/sendMessage?chat_id={id}&text={reply}".format(**{'key':the_key, 'id':my_chat_id,'reply':reply_text})
 +response = requests.get(url)
 +</code>
 +  - now, you should have got the reply from your bot <code python>
 +result = response.json()
 +send_state = result['ok']
 +send_result = result['result']
 +# chat (first_name, id, type); date:int; message_id; text
 +</code>
 +
 +====== Python and Networking related ======
 +
 +  * above is python interact with a REST API server, you can also use python to build your own REST API server to handle requests from other application, even other application over the network and internet.
 +  * implement REST API into python, you may need to use some python module like Flash, FastAPI, then you start another thread from your python application to run your REST API server.
 +  * while using Sockets method may be simpler if you just want to send some simple message between applications, as REST API, you need write all the API URL end point response.
 +  * using REST API allow your application to talk cross different application and difference device, and provide a safe gate to your important data handled by your application.
 +
  • devwiki/python.1679557187.txt.gz
  • Last modified: 2023/03/23 07:39
  • by ying