顯示具有 python 標籤的文章。 顯示所有文章
顯示具有 python 標籤的文章。 顯示所有文章

2022年11月14日 星期一

[Python] 透過python編輯文字檔

 import os


#清除檔案中的文字後關閉

f= open('/home/pi/Documents/test.txt', 'w').close()


#在現有檔案中寫入新文字

f=open('/home/pi/Documents/tmrtV05/test.txt','a')

testStr=('This texts for test \n'+

    'and TEST')

f.writelines(testStr)

f.close()


會寫入以下文字到/test.txt中

This texts for test 

and TEST


2022年10月14日 星期五

[Python]中文編碼轉換Unicode

透過python搜尋SSID時, 發現會變成Unicode,所以查了一下編碼跟解碼的方法。

SSID看來編碼方式是utf-8,但其實編碼方式蠻多的,就列出來可以看一下長相。

以下程式碼:

#coding:utf-8

import sys


chStr='中文字En'

print (chStr,type(chStr))

輸出: 

中文字En <class 'str'>

print ('-轉utf8------')

UTF8_chStr=chStr.encode('utf-8')

print (UTF8_chStr,type(UTF8_chStr))

UTF8_chStr_decode=chStr.encode('utf-8').decode('utf-8')

print (UTF8_chStr_decode,type(UTF8_chStr_decode))

輸出: 

-轉utf8------

b'\xe4\xb8\xad\xe6\x96\x87\xe5\xad\x97En' <class 'bytes'>

中文字En <class 'str'>


print ('-轉utf16------')

UTF16_chStr=chStr.encode('utf-16')

print (UTF16_chStr,type(UTF16_chStr))

UTF16_chStr_decode=chStr.encode('utf-16').decode('utf-16')

print (UTF16_chStr_decode,type(UTF16_chStr_decode))

輸出: 

-轉utf16------

b'\xff\xfe-N\x87eW[E\x00n\x00' <class 'bytes'>

中文字En <class 'str'>


print ('-轉gbk------')

gbk_chStr=chStr.encode('gbk')

print (gbk_chStr,type(gbk_chStr))

gbk_chStr_decode=chStr.encode('gbk').decode('gbk')

print (gbk_chStr_decode,type(UTF8_chStr_decode))

輸出: 

-轉gbk------

b'\xd6\xd0\xce\xc4\xd7\xd6En' <class 'bytes'>

中文字En <class 'str'>


print ('-unicode_escape------')

uni_chStr=chStr.encode('unicode_escape')

print (uni_chStr,type(uni_chStr))

uni_chStr_decode=chStr.encode('unicode_escape').decode('unicode_escape')

print (uni_chStr_decode,type(uni_chStr_decode))

輸出: 

-unicode_escape------

b'\\u4e2d\\u6587\\u5b57En' <class 'bytes'>

中文字En <class 'str'>


2022年9月26日 星期一

[Python]透過Python 程式連線無線網路- pywifi 使用

[pywifi參考網址]


概念是將無線網路參數加入wpa_supplicant.conf來進行連線,若不用語法控制,其實直接將網路資訊設定在wpa_supplicant.conf中也可以。

位置:

sudo nano/etc/wpa_supplicant/wpa_supplicant.conf


設定值:
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=TW

#無加密網路
network={
        ssid="test"
        key_mgmt=NONE
        disabled=1
}

#有加密網路
network={
        ssid="test2"
        psk="password"
        key_mgmt=WPA-PSK
}


安裝Pywifi

pip install pywifi


連線範例程式:

import pywifi

import sys

import time

from pywifi import const


wifi=pywifi.PyWiFi()

ifaces= wifi.interfaces()[0]

profiles = ifaces.network_profiles()


ifaces.disconnect()

profile=pywifi.Profile()

profile.ssid="[無線網路名稱]"

profile.key="[無線網路密碼]"

profile.auth=const.AUTH_ALG_OPEN

profile.akm.append(const.AKM_TYPE_WPA2PSK)

profile.cipher=const.CIPHER_TYPE_CCMP

#移除舊的設定參數

ifaces.remove_all_network_profiles()

#加入新的的設定參數

new_profile=ifaces.add_network_profile(profile)

time.sleep(2)

print('add profiles.ssid:'+str(profiles[0].ssid))

print('------')

#進行連線

ifaces.connect(new_profile)

#等候連線

time.sleep(10)


測試經驗是 pywifi的狀態檢查通能不太可靠,等候連線的時間可能10秒到1分鐘以上。


相關profile參數補充如下:

# Define interface status.

IFACE_DISCONNECTED = 0

IFACE_SCANNING = 1

IFACE_INACTIVE = 2

IFACE_CONNECTING = 3

IFACE_CONNECTED = 4


# Define auth algorithms.

AUTH_ALG_OPEN = 0

AUTH_ALG_SHARED = 1


# Define auth key mgmt types.

AKM_TYPE_NONE = 0

AKM_TYPE_WPA = 1

AKM_TYPE_WPAPSK = 2

AKM_TYPE_WPA2 = 3

AKM_TYPE_WPA2PSK = 4

AKM_TYPE_UNKNOWN = 5


# Define ciphers.

CIPHER_TYPE_NONE = 0

CIPHER_TYPE_WEP = 1

CIPHER_TYPE_TKIP = 2

CIPHER_TYPE_CCMP = 3

CIPHER_TYPE_UNKNOWN = 4


KEY_TYPE_NETWORKKEY = 0

KEY_TYPE_PASSPHRASE = 1


搜尋無線網路範例程式:

wifi=pywifi.PyWiFi()#建立一個wifi物件

ifaces= wifi.interfaces()[0]#取第一個無限網絡卡

print(ifaces.name())#輸出無線網絡卡名稱

ifaces.scan()

scanResult = ifaces.scan_results()

time.sleep(10)

if scanResult is not None:

    for profile in scanResult:

        ssid = profile.ssid

        print(profile)

        print('SSID:'+profile.ssid)

        print('AUTH:'+str(profile.auth))

        print('cipher:'+str(profile.cipher))

        print('AKM:'+str(profile.akm))

else:

    print ('未找到wifi')

2022年5月22日 星期日

Tinker Board 2S GPIO Input/Output Sample

Tinker Board 2S 的Image檔已經有GPIO SDK不用另外下載。

Python 安裝方法如下:

cd /usr/local/share/gpio_lib_python_rk3399

sudo python setup.py install

sudo python3 setup.py install


以下目錄有範例程式:

cd /usr/local/share/gpio_lib_python_rk3399/test/ 

(PS. 一開始我下載到Tinker Board的Library,就會出現錯誤訊息)


Tinker Board GPIO  PIN說明:



目前測試起來跟樹莓派的語法相同:

測試一個3PIN搖頭開關輸入

import ASUS.GPIO as GPIO
import time

#關閉警示
GPIO.setwarnings(False)
#設定Pin No為BOARD
GPIO.setmode(GPIO.BOARD)
#宣告Input Pin
inPort=3
GPIO.setup(inPort,GPIO.IN)
GPIO.add_event_detect(inPort, GPIO.BOTH)
#宣告一個 GND Pin
lowGnd=5
GPIO.setup(lowGnd,GPIO.OUT)
GPIO.output(lowGnd,GPIO.LOW)

#偵測Input迴圈
while True:
if GPIO.event_detected(inPort):
inputVal=GPIO.input(inPort)
print('Val:'+str(inputVal))
else:
print ('--')
time.sleep(0.5)




測試LED閃爍

import ASUS.GPIO as GPIO
import time

#關閉警示
GPIO.setwarnings(False)
#設定Pin No為BOARD
GPIO.setmode(GPIO.BOARD)
#宣告LED PIN
lightP=32
GPIO.setup(lightP,GPIO.OUT)

#開關LED迴圈
while True:
GPIO.output(lightP,GPIO.HIGH)
time.sleep(1)
GPIO.output(lightP,GPIO.LOW)
time.sleep(1)



2022年5月16日 星期一

Flask 網頁 透過下拉選單(select) 顯示不同圖片

還在摸索Flask中,感覺比較大的好處是直接就包含web Server了,

不用另外設定(Ngix, Apache..)。

不太確定有沒有前後端分離的概念,目前測試感覺都是由Flask包好再傳到前端,

速度似乎稍微慢一點。(也有可能是我還不會設定...)


範例程式:

從localhost:8080/ 頁面中的下拉選擇圖片並按下送出後,

進入另一個頁面顯示所選擇的圖片。

由於想要在顯示圖片時,也顯示下拉選單中的圖片名稱,

但不知道Python如何顯示,所以使用Jquery將選單文字加到隱藏欄位,

用Post表單的方式將文字帶出來。



Flask程式目錄下有:

- templete資料夾: 存放html檔案

- static資料夾:存放CSS、圖片、JS檔案...

- 其他就是python檔 


檔案如下:

- python檔sample.py

- 首頁 index.html(存在template中)

- 圖片頁 showImg.html(存在template中)

- CSS檔 sample.css(存在static/css中)

- 圖片檔 sample.css(存在static/images中 請自行找圖喔)

- 另外還有JQuery檔(請自行下載)


python檔: sample.py

PS. 安裝Flask (pip install flask)

from flask import render_template (存取template html資料)

from flask import request (若有透過POST, GET 傳值 則需要request)



import time
import flask
from flask import render_template
from flask import request
import netFunc

#--Flask
app = flask.Flask(__name__)

#首頁路徑Function
@app.route('/')
def index():
    #下拉選單的資料
    imgs=[
        {'val':'cat','text':'貓'},
        {'val':'flower','text':'花'},
        {'val':'rabit','text':'兔子'}
    ]
    #顯示為template中的index.html
    return render_template('index.html',**locals())

#當路徑為submit時,執行的function
@app.route('/p', methods=['POST'])
def showImg():
    #取得圖片選單的value,並加上完整路徑
    imgName=request.values['imgPick']
    imgurl='./images/'+imgName+'.jpg'
    #取得隱藏欄位的value
    imgText=request.values['tmptext']
    return render_template('showImg.html',**locals())


if __name__=='__main__':
    ip='localhost'
    app.run(host=ip,port=8080,debug=True)



首頁 index.html

<!DOCTYPE html>
<html lang='zh-TW'>
<head>
      <meta charset="utf-8" />
      <title>This Sample Page</title>
      <link type="text/css" rel="stylesheet"
          href="{{ url_for('static',filename='css/sample.css')}}" />
      <script src="{{url_for('static',filename='js/jquery-3.5.1.min.js')}}" ></script>
</head>
<body>
      <!--建立POST 方法的表單,並在送出後,將路徑加上submit-->
      <form method="post" action="/p">
            <label>選擇圖片</label>
            <div id="func">
                  <select id="picker" name="imgPick" onchange="getSelect()">
                        {% for i in imgs %}
                        <option value={{i.val}} >{{i.text}}</option>
                        {% endfor %}
                  </select>
                  <!--透過隱藏的欄位記錄選項文字-->
                  <input type="text" name="tmptext" id="tmptext" style="display:none ;"></input>
                  <button type="submit">確認</button>
            </div>
           
      </form>

</body>
</html>

<script>
      //一進入頁面就先取得選單文字並帶入表單tmptext
      $(document).ready(function(){
            selectText=$('#picker').find(':selected').text()
            $('#tmptext').val(selectText)
      })

      //透過JS取得選擇的選項文字
      function getSelect(){
            selectText=$('#picker').find(':selected').text()
            $('#tmptext').val(selectText)
      }
</script>


圖片頁 showImg.html

<!DOCTYPE html>
<html lang='zh-TW'>
<head>
      <meta charset="utf-8" />
      <title>This Sample Page</title>
      <link type="text/css" rel="stylesheet"
          href="{{ url_for('static',filename='css/sample.css')}}" />
      <script src="{{url_for('static',filename='js/jquery-3.5.1.min.js')}}" ></script>
</head>
<body>
    <div id="show">
    <a href="/">回前頁</a>
        <label >所選擇圖片為-{{imgText}}</label>
        <!--圖片會根據Python回傳得imgurl顯示-->
        <img src="{{url_for('static',filename=imgurl)}}" />
    </div>

</body>
</html>


CSS檔 sample.css


form{
    display: block;
    width: 50%;
    height: auto;
    margin: 1px auto;
    padding: 10px;
}

#func{
    margin-top: 10px;
}
label{
    font-size: 18pt;
    color: rgb(3, 84, 84);
    margin: 10px;
}

#picker{
    color: rgb(133, 50, 6);
    font-size: 14pt;
}

button{
    background-color: rgb(3, 84, 84);
    color: white;
}
#show{
    display: block;
    width: 50%;
    height: auto;
    margin: 1px auto;
    padding: 10px;
    margin-top: 10px;
    margin-bottom: 10px;
}
#show a{
    display: block;
    width: 80px;
    line-height: 30px;
    font-size: 14pt;
    text-decoration: none;
    background-color: rgb(200,210,220);
    color: rgb(80,80,80);
    border-radius: 5px;
    text-align: center;
}
#show a:hover{
    background-color: rgb(129, 168, 160);
    color: white;
    border-radius: 5px;
}
#show label{
    margin-top: 10px;
    margin-bottom: 10px;
}
img{
    margin: 10px;
}