背景
想在嵌入式linux系統上使用python3.
嵌入式平台:飛思卡爾(NXP)的IMX280 ARM7
python版本:3.7
host虛擬機:ubantu12.4 32位
編譯
python官網下載源碼包
編譯host虛擬機中運行的python
因為等一下交叉編譯的時候要用到。編譯比較簡單
- ./configure --prefix=/home/bert/python3.7-x86
- make
- make install
- ln -s /home/bert/python3.7-x86/bin/python3.7 /usr/bin/python3
報錯:No module named '_ctypes'
解決:sudo apt-get install libffi.dev
編譯arm版本的python
編譯arm版本比較麻煩,寫一個config腳本,名為bertconfig-arm.sh。
#!/bin/sh arm_build=`pwd`/arm_build mkdir $arm_build cd $arm_build echo ac_cv_file__dev_ptmx=yes > config.site echo ac_cv_file__dev_ptc=yes >> config.site export CONFIG_SITE=config.site ../configure \ CC=/opt/freescale/usr/local/gcc-4.1.2-glibc-2.5-nptl-3/arm-none-linux-gnueabi/bin/arm-none-linux-gnueabi-gcc \ CXX=CC=/opt/freescale/usr/local/gcc-4.1.2-glibc-2.5-nptl-3/arm-none-linux-gnueabi/bin/arm-none-linux-gnueabi-g++ \ AR=/opt/freescale/usr/local/gcc-4.1.2-glibc-2.5-nptl-3/arm-none-linux-gnueabi/bin/arm-none-linux-gnueabi-ar \ READELF=/opt/freescale/usr/local/gcc-4.1.2-glibc-2.5-nptl-3/arm-none-linux-gnueabi/bin/arm-none-linux-gnueabi-readelf \ STRIP=/opt/freescale/usr/local/gcc-4.1.2-glibc-2.5-nptl-3/arm-none-linux-gnueabi/bin/arm-none-linux-gnueabi-strip \ --host=arm-none-linux-gnueabi \ --build=i686-linux-gnu \ --target=arm-none-linux-gnueabi \ --disable-ipv6 \ --prefix=/home/bert/python3.7-arm exit 0
- make clean
- ./bertconfig-arm.sh
- make
- make install
瘦身
編譯通過后arm版python160M+,我的嵌入式產品flash才150M空間,沒法用,要瘦身。
刪除不必要的文件
- 刪除include和share文件夾
- bin和lib下面僅留下python3.7
- /lib/python3.7下刪除所有test和config相關的文件
strip縮小體積
將 bin下的python3.7 和lib/python3.7下的所有.so strip,基本可以減小一半的體積
- arm-strip /bin/python3.7
- arm-strip /lib/python3.7/lib-dynload/*.so
將.py轉換成.pyc文件
其實__pycache__里面放的是.py自動生成的.pyc文件,現在手動轉換后,就可以減小一半的空間。
- python3 -m compileall . -b
- 刪除__pycatche__和所有.py
經過以上步驟,體積縮小到50M左右勉強可以用啦。
其他思路:
創建zip版本的lib:可以是可以,但是運行的時候還是要解壓呀,增加第三方庫的時候也不方便吧?
使用其他壓縮軟件:比較麻煩吧,不知道會不會影響性能。
終極瘦身之最小python
lib下面有好多包,並非都是必須的,例如在沒有顯示屏的arm中,要tkinter作甚?
- lib/python3下面保留lib-dynload(動態庫)和os.pyc這兩個文件
- 在arm系統上運行bin/python3.7,提示差什么包就把什么包復制過去
最終lib結構如下:
-rw-r--r-- 1 bert bert 29K Oct 11 02:37 _collections_abc.pyc
-rw-r--r-- 1 bert bert 3.4K Oct 11 02:37 _sitebuiltins.pyc
-rw-r--r-- 1 bert bert 6.3K Oct 11 02:37 abc.pyc
-rw-r--r-- 1 bert bert 34K Oct 11 02:37 codecs.pyc
drwxr-xr-x 3 bert bert 12K Oct 11 04:12 encodings
-rw-r--r-- 1 bert bert 3.7K Oct 11 02:37 genericpath.pyc
-rw-r--r-- 1 bert bert 3.3K Oct 11 02:37 io.pyc
drwxr-xr-x 2 bert bert 4.0K Oct 12 2019 lib-dynload
-rw-r--r-- 1 bert bert 29K Oct 11 02:37 os.pyc
-rw-r--r-- 1 bert bert 11K Oct 11 02:37 posixpath.pyc
-rw-r--r-- 1 bert bert 17K Oct 11 02:37 site.pyc
-rw-r--r-- 1 bert bert 3.8K Oct 11 02:37 stat.pyc
現在只有13M了,完全滿足我的要求。
encodings文件夾下面肯定可以繼續縮減,不過已經超出我的需求了,到此為止。
參考
好多一鍵移植的方法,我個人覺得,在linux里面,No way.
不得不說的兩篇好文章供參考:
編譯:https://blog.csdn.net/u012230668/article/details/89206857
瘦身:https://blog.csdn.net/yyw794/article/details/78059183