顯示具有 Python 3 程式語言 標籤的文章。 顯示所有文章
顯示具有 Python 3 程式語言 標籤的文章。 顯示所有文章

2022年8月1日 星期一

Jupyter notebook 延伸工具

 

超好用的2個Jupyter notebook 延伸工具
  • Table of content : 針對Markdown cell 提供目錄
  • autopep8:  python代碼格式化工具






(2) 安裝 Jupyter notebook extensions

打開Anaconda Prompt  , 執行

pip install jupyter_contrib_nbextensions && jupyter contrib nbextension install

(3) 重新開啓Jupyter Notebook, Enable "Table of content "






2018年10月25日 星期四

安裝jupyter notebook 於Raspberry Pi







1.) 安裝 jupyter notebook 

sudo pip3 install jupyter   

(約等個15分鐘吧..耐心等候)

2.) 讓 jupyter-notebook Server 可從windows連入

==> jupyter notebook --generate-config

#修改 ~/.jupyter/jupyter_notebook_config.py 找到
#c.NotebookApp.ip = ‘localhost'

改成

c.NotebookApp.ip = '0.0.0.0’ 





# 設定瀏覽器登入 jupyter notebook server密碼

==> jupyter notebook password

3.)啓動jupyter-notebook 


sudo jupyter-notebook

如果是root ,則要多加 --allow-root 才能啓動    sudo jupyter-notebook --allow-root     





4.) 在windows上,打開瀏覽器連入

http://192.168.1.252:8888/


Note: 192.168.1.252 為 Pi的Ethernet IP, 也可以用Wi-Fi 的IP連入, 只要那個IP是Windows能連到的即可 (同一個router所配的IP都OK!)

如何查Pi的IP?  請執行ifconfig  ==> 查看Pi網路IP 

(更多Pi 的基礎操作, 請看課程學習 )




 成功登入 jupyter notebook畫面~



 看一下 jupyter notebook kernel 使用的python 版本






2018年6月26日 星期二

Invalid MIT-MAGIC-COOKIE-1 ??



python3 tkui.py 直接執行可以..但是無法在開機時自動執行, 原因是執行X Window應用程式(X X Client),若要能連接到X Server 時, X Client 必須要提供兩個設置


  1. 設置遠端 XServer  DISPLAY 環境變數。
    export DISPLAY=:0.0
  2. 能讀到 Xauthority下的cookie檔 ( 位在每個user 的HOME目錄的.Xauthority 目錄)
    export XAUTHORITY=/home/<YOUR-USER-NAME>/.Xauthority


通常用自己登入帳號去執行X Client 程式沒有問題, 但若不是或經由 sudo 去執行,則必須設定  Xauthority的位置.


用pi 帳戶, 執行 python3 tkui.py 沒有問, 但是用 sudo python3 tkui.py 會出現錯誤

例如:

pi@raspberrypi:~ $ sudo python3 tkui.py
Invalid MIT-MAGIC-COOKIE-1 keyInvalid MIT-MAGIC-COOKIE-1 keyTraceback (most recent call last):
  File "tkui.py", line 16, in <module>
    win=Tk.Tk()
  File "/usr/lib/python3.5/tkinter/__init__.py", line 1880, in __init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: couldn't connect to display ":0.0"



解決方式: 

pi@raspberrypi:~ $ export XAUTHORITY=/home/pi/.Xauthority
pi@raspberrypi:~ $ sudo python3 tkui.py   ==> 能正常執行,因為能找到Xauthority 檔案



References:

https://iwf1.com/quick-fix-invalid-mit-magic-cookie-1-sudo




2018年6月24日 星期日

使用pyserial讀取Serial資料










Trouble Shooting


 pip3 install pyserial

Traceback (most recent call last):
  File "serial.py", line 1, in <module>
    import serial
  File "/home/pi/serial.py", line 3, in <module>
    port = serial.Serial("/dev/ttyUSB0", baudrate=9600, timeout=3.0)
AttributeError: module 'serial' has no attribute 'Serial'

解法:  pip3 uninstall serial

>>> import serial
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: bad magic number in 'serial': b'\x03\xf3\r\n'

解法:  find . -name \*.pyc -delete




https://goo.gl/EcCcj7

2018年6月7日 星期四

[Raspberry pi] Python GUI Tkinter



如何執行?
export DISPLAY=:0.0
python3 tkui.py













----------------------------------------------

Create GUI with TKInter over SSH

這一行, 就可以用SSH開發GUI程式, 讓視窗畫面出現在LCD上


export DISPLAY=:0.0

----------------------------------------------

RPi 4"Inch 480x320 LCD (SPI 界面)

2017年11月22日 星期三

.py 和 ipython notebook (.ipynb) 互轉?









1) 如何將 xxx .py 轉成 xxx.ipynb ?

在jupyter  notebook , 在一個cell 上執行

%load relu.py

就可以將relu.py 程式碼讀入, 然後再存檔, 就會自動存成了 relu.ipynb 了!









2) 如何將 xxx .ipynb 轉成 xxx.py ?



若有很多.ipynb 要轉換成.py , 可以執行下列命令
(在juypter notebook 下, 開啓一個程式cell來執行, 將hw3,ipynb --> hw3.py )


!jupyter nbconvert --to script hw3.ipynb









https://goo.gl/EcCcj7


2017年10月3日 星期二

Python 處理Excel (.csv) 欄位計算使用Numpy




Python 處理Excel (.csv) 欄位計算使用Numpy



Numpy是Python用來科學計算的一個非常重要的函式庫,numpy主要用來處理一些矩陣對象,可以說numpy讓Python有了Matlab功能。

import numpy as np

p.s  使用numpy 要先安裝此module
   pip3 install numpy

產生5x7陣列
a = np.arange(35).reshape(5,7)
print(a)


[[ 0  1  2  3  4  5  6]
 [ 7  8  9 10 11 12 13]
 [14 15 16 17 18 19 20]
 [21 22 23 24 25 26 27]
 [28 29 30 31 32 33 34]]


取出特定cell的值
print(a[2,4])


18

取出特定列
print(a[0:3,:])  #取出某些列中的全部欄位 從第0列~第3列



[[ 0  1  2  3  4  5  6]
 [ 7  8  9 10 11 12 13]
 [14 15 16 17 18 19 20]]


取出特定列、欄
print(a[0:3,0:4]) 
# [start:end:step] 用來連續抓取一塊矩陣範圍, 可以使用step參數 (step=1,2,3...) , 預設step=1 (step=1可以不寫)


[[ 0  1  2  3]
 [ 7  8  9 10]
 [14 15 16 17]]

print(a[1:5:2,::3])   #row : 1,3 ; column: no start, so start(0):no end:step 3==> 0,3,6,....
[[ 7 10 13]
 [21 24 27]]


取出特定欄
print(a[:,1])     #start 不寫表示從0開始, end不寫表示算到最後  [ 1  8 15 22 29]



[ 1  8 15 22 29]

取出多個特定欄位
print(a[:,[1,3,4]])  #取出所有列中的某些特定欄, 第1欄, 第3欄,第4欄


[[ 1  3  4]
 [ 8 10 11]
 [15 17 18]
 [22 24 25]
 [29 31 32]]


欄位相乘
f1,f2=1,2
y1=a[:,f1]
y2=a[:,f2]
y=y1*y2
print(y)  


[  2  72 240 506 870]

找最大值 print(np.max(y))


870

找最小值

print(np.min(y))


2

陣列元素值加總
print(np.sum(y))


1690

陣列元素四捨五入
np.around([0.55, 0.65, 0.05], decimals=1)

array([0.6, 0.6, 0.0])


[python] numpy meshgrid



numpy


numpy
import numpy as np
import matplotlib.pyplot as plt

#plt.axis([0, 6, 0, 20])

xvalues = np.array([1,2,3,4]);
yvalues = np.array([5,6,7]);
xx, yy = np.meshgrid(xvalues, yvalues)
print(xx)
print(yy)
plt.plot(xx, yy, marker='.', color='k', linestyle='none')
plt.show()


[[1 2 3 4]
 [1 2 3 4]
 [1 2 3 4]]
[[5 5 5 5]
 [6 6 6 6]
 [7 7 7 7]]










2017年9月26日 星期二

Python 函式使用 (四)


Pyton 函數呼叫

函數定義

def function_name (a,b):
...  
...  
...  return xxxxx


全域變數vs 區域變數


  1. 全域變數: 變數宣告在任何函數外,即為全域變數
  2. 區域變數: 定義在函數內部的變數, 非def 內無法存取此區域變數
  3. Python 函數可以直接存取(直接用或操作)全域變數 (不必傳參數)
  4. 小心: 若宣告區域變數與全域變數的名稱相同, 則以區域變數為主, 若函數內要使用外部的全域變數, 必須用global 關鍵字, 表示其參考外部的全域變數,而非重新定義的區域變數


# 全域變數vs 區域變數

x1=[2,4,6]
a=5

def func1():
    x1[1]=100   #存取會更改x1

def func2(): 
    x1=[1,2,3]    #初值設定,宣告變數x1 (和global x1相同, 故此為Local Variable )
    print(x1)    #[1, 2, 3]
    
def func3():
    a=10     #屬初值設定而非更改變數,因為是宣告, 則變數a為Local (雖然和global a相同
    print(a)

    
def func4():
    global a
    a=10      #初值設定為local, 但global明確定義a是global
    print(a)  #10

    
def func5():
    global x1
    x1=[1,2,3]    #初值設定:x1是local

 
func1()
print(x1)   #[2, 100, 6]
func2()
print(x1)  #[2, 100, 6]
func3()
print(a)   #5
func4()
print(a)  10
func5()
print(x1)  [1, 2, 3]


lambda Function
 
Python提供了一個簡易的function define:lambda,用完即丟,不著痕跡。讓你實作出很簡單的function (只處理一個運算式)


語法:
ambda argument_list: expression 

def func(x, y, z):
    return x + y + z

func2 = lambda x,y,z : x+y+z

print(func(1,2,3))       
print(func2(1,2,3))    


map 
Function

map() is a function which takes two arguments: 
r = map(func, seq)

The first argument func is the name of a function and the second a sequence (e.g. a list) seqmap() applies the function func to all the elements of the sequence seq. Before Python3, map() used to return a list, where each element of the result list was the result of the function func applied on the corresponding element of the list or tuple "seq". With Python 3, map() returns an iterator. 
my_list = [1, 2, 3]
ans=list(map( lambda i: i * i, my_list ))  
print(ans)  


[1, 4, 9]

不定個數參數函數用法


#不定個數參數 * (tuple)


def hello(*names):
    for n in names
        print("Hello, %s."%n)

names_tuple=("Tom","Peter","Bob","Rain")  
hello(*names_tuple)
hello("Tom","Peter","Bob","Rain")



#不定個數參數 ** (dict)

def hello(**names):
    for n in names:
        print("Hello %s, you're %d years old"%(n,names[n]))

names_dict={'John':25, 'Tom':20, 'Bob':33, 'Tony':18}
hello(**names_dict)
hello(John=25, Tom=20, Bob=33, Tony=18)



















2017年8月23日 星期三

Python 入門學習快速筆記 (六)


例外處理 try: ... excpet:



a=100
b=10

try:
    c=a/b
    print("c=",c)
except:
    c=-1
    print("Divdie by zero")
    print("c=",c)

print("c=",c)

------------------
try-except 也可以和 else 連用, else 後的程式區塊放的是沒有發生例外,程式所執行的工作,例如
try:
    c=a/b
    print("c=",c)
except:
    c=-1
    print("Divdie by zero")
    print("c=",c)
else:
    print("No exception")
-----------------------------------------------
例外的名稱也可以寫在 except 之後,如
try:
    c=a/b
    print("c=",c)
except ZeroDivisionError:
    c=-1
    print("Divdie by zero")
    print("c=",c)
except NameError:
except TypeError:
except IndexError:

-----------------------------
若加入另一個關鍵字 finally ,無論例外有沒有發生都會執行 finally 後的程式區塊
try:
    c=a/b
    print("c=",c)
except ZeroDivisionError:
    c=-1
    print("Divdie by zero")
    print("c=",c)
except NameError:
except TypeError:
except IndexError:
findally:

--------------------------

Raise 觸發Exception Error


try:
raise NameError
     
except NameError:
        print("發生例外,NameError")
except ZeroDivisionError:
print("發生例外,ZeroDivisionError")


print("after exception....")

Python 所有Exception
https://docs.python.org/3/library/exceptions.html#exception-hierarchy



Python檔案處理


file = open('dream.txt', 'r', encoding='UTF-8')

li=file.readlines()
print(li[3],end='')



Python 第三方套件



https://pypi.python.org/pypi?:action=browse&c=533&show=all

安裝 Python 第三方套件-使用pip 工具
C:\Python34\Scripts>pip install pyqrcode

Collecting pyqrcode
  Downloading PyQRCode-1.1.tar.gz
Building wheels for collected packages: pyqrcode
  Running setup.py bdist_wheel for pyqrcode
  Stored in directory: C:\Users\student\AppData\Local\pip\Cache\wheels\03\93\7f\
d3a38165d01798524d99329a6aabba2b378d81da1d46f15b36
Successfully built pyqrcode
Installing collected packages: pyqrcode
Successfully installed pyqrcode-1.1

C:\Python34\Scripts>pip install pypng


#-*-coding:UTF-8 -*-
#  EX08_01.py
#  
#  pyqrcode 使用範例
#  
from pyqrcode import QRCode
url = QRCode('http://www.ntu.edu.tw')
#輸出SVG格式檔案:url.svg ,縮放比為10
url.svg('url.svg', scale=10)
#輸出PNG格式檔案:url.png ,縮放比為10

url.png('url.png', scale=10)






2017年3月9日 星期四

Python 入門學習快速筆記 (五)

類別

class Demo:
   
        i=0   # 類別變數
        def __init__(self, name):
                self.name=name    # self.name 實體變數
        def showvalue(self):
                print("hello",self.i)

        def showname(self):
                print("hello",self.name)


private variable 或 private_method 在名稱前面加上 __
__variable
__function

Private value

Traceback (most recent call last): File "C:/Python34/aaa.py", line 33, in <module> print(a.__y) # private attribute AttributeError: 'Demo' object has no attribute '__y'



200 Traceback (most recent call last): File "C:/Python34/aaa.py", line 25, in <module> print(a.i) AttributeError: 'Demo' object has no attribute 'i'


Traceback (most recent call last): File "C:/Python34/aaa.py", line 25, in <module> print(a.__i) AttributeError: 'Demo' object has no attribute '__i'

==========================================


封裝 


public data, private datapublic function, private function


==========================================


類別多重繼承

子類別(subclass)能夠繼承(inherit) 多個父類別,使子類別可以有多種特性。
  • 當子類別繼承(inheritance)超過一個來源的時候,會以寫在最左邊的父類別優先繼承,這是說,多個父類別如果有相同名稱的屬性(attribute)與方法(method),例如init()、str__()等,就會以最左邊的父類別優先。


==========================================

多型(polymorphism) 與抽象方法( Abstract method)


class Animal: def __init__(self, name): # Constructor of the class self.name = name def talk(self): # Abstract method, defined by convention only raise NotImplementedError("Subclass must implement abstract method") class Cat(Animal): def talk(self): return 'Meow!' class Dog(Animal): def talk(self): return 'Woof! Woof!' class Fish(Animal): pass animals = [Cat('Missy'), Cat('Garfield'), Dog('Lassie'),Fish('Gold')] for animal in animals: print(animal.name + ': ' + animal.talk())


Traceback (most recent call last): File "D:\Python_lecturer_NTU\python code\python code\EX05_08.py", line 20, in <module> print(animal.name + ': ' + animal.talk()) File "D:\Python_lecturer_NTU\python code\python code\EX05_08.py", line 5, in talk raise NotImplementedError("Subclass must implement abstract method") NotImplementedError: Subclass must implement abstract method







2015年8月3日 星期一

Python程式-格式化輸出與字串處理 (三)


格式化輸出 Print: 結構語法基本上同C/C++語言printf


>>> a=4
>>> b=5

>>> print('a=%d'%a)
a=4
>>> print(a,'*',b,'=',a*b)
4 * 5 = 20

一個以上的%d 輸出
>>> print('%d*%d=%d'%(a,b,a*b))
4*5=20

# 多了和C不一樣的功能, 可以用dict的結構,用key找對應的value來輸出
>>> print('%(#2)d*%(#1)d=%(#v)d'%{'#1':a,'#2':b,'#v':a*b})
5*4=20


>>> print('a=%d'%a)
a=4
>>> print('a=%10d'%a)  # 空10格
a=         4
>>> print('a=%010d'%a)  # 空10格且前面補0
a=0000000004

卬浮點數 %f
>>> money=172.85
>>> print('%f',money)
%f 172.85

>>> print('%f'%money)
172.850000

>>> print('$%6.2f''%money)
$172.85

>>> print('$%*.2f'%(10,money)) # 空10格
$         172.85

字串函數


>>> text='it robotic lab'
>>> text.capitalize()
'It robotic lab'
>>> text
'it robotic lab'

>>> text=text.capitalize()  #存回text
>>> text
'It robotic lab'

Python 流程控制(二)



if 

>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...     x = 0
...     print('Negative changed to zero')
... elif x == 0:
...     print('Zero')
... elif x == 1:
...     print('Single')
... else:
...     print('More')
...

for 

>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
...     print(w, len(w))
...
cat 3
window 6
defenestrate 12


>>> for w in words[:]:  # Loop over a slice copy of the entire list.
...     if len(w) > 6:
...         words.insert(0, w)
...
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']


Range (n) 產生0~n-1序列


>>> for i in range(5):
...     print(i)
...
0
1
2
3
4

a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
     print(i, a[i])

0 Mary
1 had
2 a
3 little
5 lamb


while 

a = ['Mary', 'had', 'a', 'little', 'lamb']
i=0
while i < len(a):
    print(i, a[i])
    i+=1
0 Mary 1 had 2 a 3 little 4 lamb