發表文章

目前顯示的是有「Python」標籤的文章

修正python3.12-venv相依關係python3.12無法修正問題,您保留了損毀的套件

圖片
這是我從Ubuntu升級22.04 (Jammy Jellyfish)到24.04 (Noble Numbat) 遭遇的問題之一。因為python3版本從3.10改成3.12,所以套件也需要重新安裝。 python3.12-venv:相依關係:python3.12 (=3.12.3-1ubuntu0.13) 但 3.12.7-1+jammy1 卻將被安裝 E: 無法修正問題,您保留(hold)了損毀的套件。

pyhon用matplotlib畫圖範例與設定字體

Python使用matplotlib畫圖範例 import matplotlib.pyplot as plt import numpy as np import os import zipfile # UserWarning: Glyph 26371 (\N{CJK UNIFIED IDEOGRAPH-6703}) missing from font(s) DejaVu Sans. from matplotlib import font_manager font_path = "/usr/share/fonts/opentype/noto/NotoSerifCJK-Medium.ttc" # 修改為字體實際路徑 font_prop = font_manager.FontProperties( fname = font_path) plt.rcParams[ "font.family" ] = font_prop.get_name() # Chart 1: 全球市場規模成長趨勢(折線圖) years = [ 2020 , 2024 , 2030 ] values = [ 60 , 280 , 1800 ] # 單位:十億美元 plt.figure() plt.plot(years, values, marker = 'o' , linestyle = '-' , color = 'blue' ) plt.title( "全球 AI 市場規模成長(十億美元)" ) plt.xlabel( "年份" ) plt.ylabel( "市場規模" ) plt.grid( True ) plt.tight_layout() # Prepare folder for images img_dir = "./ai_charts" os.makedirs(img_dir, exist_ok = True ) plt.savefig( f " { img_dir } /01_market_growth.png" ) plt.close()   Python列出matpl...

抓取主機的IP(含IPv4和IPv6)

抓取主機的IP(IPv4和IPv6) Python部份 import socket addrs = socket.getaddrinfo('www.hinet.net',443) ipv4_addrs = list(set([addr[4][0] for addr in addrs if addr[0] == socket.AF_INET])) ipv6_addrs = list(set([addr[4][0] for addr in addrs if addr[0] == socket.AF_INET6])) print ('first IPv4:', ipv4_addrs[0], ' candidates:', len(ipv4_addrs)) print ('first IPv6:', ipv6_addrs[0], ' candidates:', len(ipv6_addrs)) 以上程式碼測試過python 3.5.2和python 2.7.12 輸出為: first IPv4: 210.61.33.225  candidates: 8 first IPv6: 2001:b000:1e5:1100::8  candidates: 8 BASH部份 $ nslookup -querytype=A www.hinet.net $ nslookup www.hinet.net Server:   127.0.1.1 Address:  127.0.1.1#53 Non-authoritative answer: www.hinet.net canonical name = hinet-hp.cdn.hinet.net. Name: hinet-hp.cdn.hinet.net Address: 210.61.33.229 Name: hinet-hp.cdn.hinet.net Address: 210.61.33.227 Name: hinet-hp.cdn.hinet.net Address: 210.61.33.232 Name: hinet-hp.cdn.hinet.net Address: 210.61.33.231 Name: hinet...

測試AppsScript使用的python程式

這裡感謝Taylor提供的幫助 python 3.5.2 版本 程式碼如下: #!/usr/bin/python3 # -*- encoding: utf-8 -*- try:     # for python 3.5.2     import urllib.parse     import urllib.request except AttributeError:     import urllib query_method = 0 test_url = "你的測試URL" param_obj = {     "m":"123456", } if 0 == query_method:     # POST method     form_data = urllib.parse.urlencode(param_obj).encode('utf-8')     req = urllib.request.Request(test_url, form_data)     print('query url:', test_url)     with urllib.request.urlopen(req) as f:         status = f.status         resp = f.read().decode('utf-8') elif 1 == query_method:     # GET method     params = urllib.parse.urlencode(param_obj)     req_url = "%s?%s" % (test_url, params)     print('query url:', req_url)     with urllib.request.urlopen(req...

PYTHON小程式:收Multicast/IGMP封包存到檔案

接收Multicast/IGMP封包到檔案 ref: https://pymotw.com/2/socket/multicast.html

python3.5版設定request的不會顯示debug log的解法

有人問為何3.4版就可以顯示http request的log import http.client http.client.HTTPConnection.debuglevel = 1 從 這裡 看起來是設定debug level有問題,實測3.5版,3.6版都有受影響 平常 import urllib. request import http.client http.client.HTTPSConnection.debuglevel = 1 response = urllib.request.urlopen('https://www.google.com') print('status:', response .status) 解法 import urllib. request handler = urllib.request.HTTPSHandler(debuglevel=1) opener = urllib.request.build_opener(handler) response = opener.open('https://www.google.com') print('status:',response.status) 參考: https://stackoverflow.com/questions/42876579

針對requests套件強迫使用IPv4

參考 stackoverflow 和urllib3的原始碼改寫的結果

BASH新增一行字到檔案

新增文字到檔案第2行 $ sed '2i # -coding=utf-8' -i runpy.py

筆記:Python的requests除錯

1.察看某python模組版本號 https://stackoverflow.com/questions/20180543 以requests模組為例 在BASH $ pip freeze | grep requests requests==2.23.0 在python shell >>> import requests >>> print(requests.__version__) 2.23.0 2. 顯示Request的詳細資訊 https://blog.anank.ke/w/Enable-Debug-Mode-for-Requests 加入程式碼 import logging try:     from http.client import HTTPConnection except ImportError:     from httplib import HTTPConnection HTTPConnection.debuglevel = 1 logging.basicConfig() logging.getLogger().setLevel(logging.DEBUG) requests_log = logging.getLogger("requests.packages.urllib3") requests_log.setLevel(logging.DEBUG) requests_log.propagate = True 執行時在螢幕上可看到 送出的request在 send: 'POST /..... server回覆的http response reply: 'HTTP/1.1 XXX ..... 回覆的header header: Content-Type: .... 其實requests的回覆也可以在程式中取得 resp = requests.get(in_url) print ('URL:',      resp.url) print ('status:',   resp.status_code) print ('hea...

Ubuntu 16.04安裝新版pip和pip3後無法執行(No such file or directory)

在進行pip install時python會建議安裝新版本pip,雖然可以透過pip install pip進行升級就好,但是如果用sudo升級pip會發生pip指令無法使用的狀況。(指令如下) sudo pip install --upgrade pip sudo pip3 install --upgrade pip 這是因為原本Ubuntu的pip指令是透過用apt-get安裝,pip在10.0.0版本有做一些改變,所以指令有改動,導致pip自我安裝新版後無法使用pip指令 預設Ubuntu 16.04安裝的pip應該是8.1.1版,用pip -V可顯示版本 pip 8.1.1 from /usr/lib/python2.7/dist-packages (python 2.7) (2020-03-02 pip,pip3更新到20.0.2) $ pip3 -V pip 20.0.2 from /usr/local/lib/python3.5/dist-packages/pip (python 3.5) $ pip -V pip 20.0.2 from /usr/local/lib/python2.7/dist-packages/pip (python 2.7) 解法1. 修改Ubuntu內pip或pip3指令 sudo vim /usr/bin/pip 改寫成 #!/usr/bin/python # for pip > 10.0.0 import sys from pip import __main__ if __name__ == '__main__':     sys.exit(__main__._main()) 原本Ubuntu原本出問題的pip內容是 #!/usr/bin/python # -*- coding: utf-8 -*- import re import sys from pip._internal.cli.main import main if __name__ == '__main__':     sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '',...

Ubuntu 14.04編譯安裝python2.7.9

Ubuntu 14.04編譯安裝python2.7.9 請使用下面gist script, 執行時需要sudo這個script 然後發現系統的python2.7.6還是存在/usr/bin/python, 部份script指定這個路徑後依然跑舊的版本, 所以先備份2.7.6 sudo mv /usr/bin/python2.7 /usr/bin/python2.7.bak 接著設定新的為預設啟用 sudo update-alternatives --install /usr/bin/python python /usr/local/bin/python2.7 2 sudo update-alternatives --install /usr/bin/python python /usr/bin/python2.7.bak 1 sudo update-alternatives --install /usr/bin/python2 python2 /usr/local/bin/python2.7 2 sudo update-alternatives --install /usr/bin/python2 python2 /usr/bin/python2.7.bak 1 sudo update-alternatives --install /usr/bin/python2.7 python2.7 /usr/local/bin/python2.7 2 sudo update-alternatives --install /usr/bin/python2.7 python2.7 /usr/bin/python2.7.bak 1

python轉換IP/Port成Inet和mac數值轉換

判斷 endian https://stackoverflow.com/questions/1346034/ import sys sys.byteorder 'little' IP/Port和INET之間的轉換 http://blog.csdn.net/fan_hai_ping/article/details/8435140  socket.inet_aton("192.168.1.1") '\xc0\xa8\x01\x01'  addr = socket.inet_aton("192.168.1.1")  type(addr) import socket  addr = socket.inet_aton('127.0.0.1')  addr '\x7f\x00\x00\x01' >>> socket.inet_ntoa(addr) '127.0.0.1' 轉換port socket.htons(0x1234) 13330 socket.ntohs(0x1234) 13330  socket.ntohs(1234) 53764  socket.htons(1234) 53764 取得目前host ip https://www.pythonsheets.com/notes/python-socket.html  import socket  socket.gethostname() 'MacBookPro-4380.local'  hostname = socket.gethostname()  socket.gethostbyname(hostname) '172.20.10.4'  socket.gethostbyname('localhost') '127.0.0.1' MAC數值轉換 import binascii  mac = '00:11:32:3c:c3:0b'  byte = binascii.unhexlify(mac.rep...

Python手寫檔案伺服器延伸內容

應用上一篇的 Python檔案伺服器 ,我們還可以寫一些不同的回應,像是.. 1. 回應Client端要求HTML檔案 def responseHtmlFile(hdl, path):     f = open(path, "rb")     fs = os.fstat(f.fileno())     hdl.send_response(200)     hdl.send_header("Content-type", "text/html; charset=UTF-8")     hdl.send_header("Content-Length", str(fs[6]))     hdl.send_header("Last-Modified", hdl.date_time_string(fs.st_mtime))     hdl.end_headers()     shutil.copyfileobj(f, hdl.wfile)     f.close()     del f 用法: responseHtmlFile(hdl, '/home/user/your_html_file.htm') 2. 回應Client端,要求轉址到另一個目標位置 def responseHttpRedirect(hdl, target):     hdl.send_response(301)     hdl.send_header("Location", target)     hdl.end_headers() 用法: responseHttpRedirect(hdl, 'http://www.google.com') 3. 把Client的request資訊parse後再回應給Client def responseGetRequest(hdl):     parsed = urlparse(hdl.path)     hdl.se...

用Python手寫檔案伺服器

這是一個用Python寫的迷你檔案伺服器, 有在Ubuntu上測試過python2.7和python3.4版都可以使用。 如果要接受所有來源的ThisServerIp請使用0.0.0.0作為Server位址 如果要當作一般的網站ThisServerPort請使用80 要提供下載的檔案請把絕對路徑寫在DownloadFilePath1和DownloadFilePath2上 執行的方法 1. For Windows python.exe MyServer.py 2. For Ubuntu python MyServer.py 測試用URL http://127.0.0.1:8080/GetFileInfo http://127.0.0.1:8080/GetFileInfo?name=file1 http://127.0.0.1:8080/GetFileInfo?name=file2 http://127.0.0.1:8080/DownloadFile1 http://127.0.0.1:8080/DownloadFile2 GetFileInfo沒有指定參數name的時候會回應json格式的資訊 DownloadFile1, DownloadFile2是直接下載script指定的檔案 檔案伺服器MyServer.py #!/usr/bin/python # coding=utf-8 import os.path, sys import hashlib, json, shutil if sys.version_info >= (3,0):     from urllib.parse import parse_qs     from http.server import SimpleHTTPRequestHandler,BaseHTTPRequestHandler,HTTPServer else:     from urlparse import parse_qs     from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer     f...

秀出指定檔案的git hash值

雖然知道git也是用sha1演算法產生hash code,但是一直覺得怎麼跟sha1sum指令產生出的結果不同,goolge後才知道git因為還有加入其他參數所以才會讓他和sha1sum產生出的結果不一樣。 下面的小程式是秀出指定檔案的git hash值 #!/usr/bin/python import sys, os from hashlib import sha1 # emulate the behavior # > git hash-object  < file-path > def githash(filepath):     filesize_bytes = os.path.getsize(filepath)     s = sha1()     s.update(("blob %u\0" % filesize_bytes).encode('utf-8'))     with open(filepath, 'rb') as f:         s.update(f.read())     return s.hexdigest() if __name__ == '__main__':     argc = len(sys.argv)     if argc < =1:         print 'Should give at least one file path!'         sys.exit(1)     for f in sys.argv[1:]:         print f,"\t",githash(f) 由於git show時內會顯示檔案的sha1sum,但是都我們自己打sha1sum 的結果不同, 原因是git得sha1會加上描述檔案類型的字串和檔案size在檔案內容前面,之後再計算sha1sum,所以數值才會不同 參考資料:...

在Ubuntu開發OpenCV Python程式

Ubuntu安裝 python2的OpenCV 套件 sudo apt-get install python-numpy python-opencv  顯示test.jpg圖片 , 如果有參數,就用參數上的圖片 #!/usr/bin/python import sys import os.path import cv2 if __name__ == '__main__':     win_name = "Image Window"     img_path = "test.jpg"     argc = len(sys.argv)     if argc > 1:         img_path = sys.argv[1]     if not os.path.exists(img_path):         print 'File not found, path=\'', img_path, '\''         quit(-1)     print 'Show the image in the path=\'', img_path, '\''     img = cv2.imread(img_path)     if img is None:         print 'Not supported image type!'         quit(-1)     cv2.namedWindow(win_name)     cv2.imshow(win_name, img)     cv2.waitKey(0)     cv2.destroyAllWindows() Ope...