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

2018年5月8日 星期二

2018年4月20日 星期五

2018年4月13日 星期五

[Python] 9x9 multiplication table

import os
import sys


def main():
    #For loop to show 9 X 9 matrix
    for i in range(1, 10, 1):
        for j in range(1, 10, 1):
            print(i * j, end=" ")
        print()


if __name__ == '__main__':
    main()


class multiplication():
    def table():
        #For loop to show 9 X 9 matrix
        for i in range(1, 10, 1):
            for j in range(1, 10, 1):
                print(i * j, end=" ")
            print()

if __name__ == '__main__':
        a = multiplication
        a.table()
        


Use list to rewrite

class multiplication():
    def table():
        num1 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
        num2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
        #For loop to show 9 X 9 matrix
        for i in range(0, 9, 1):
            for j in range(0, 9, 1):
                print(num1[i] * num2[j], end=" ")
            print()

if __name__ == '__main__':
        a = multiplication
        a.table()

Ref:

2017年11月8日 星期三

[Python] Install virtualenv package

Method 1:
Create virtual environment under python3
python3 -m venv virtualenv (virtualenv = folder name)

Start to use virtual environment
source virtualenv/bin/activate

Method 2:
pip install virtualenv

This creates a directory called virtualenv

virtualenv --distribute virtualenv

Activate the environment variable settings:
source virtualenv/bin/activate

Reference:

[Python] Python virtual environment lib path

Method 1:

Download RPi.GPIO 0.6.3

tar xvf RPi.GPIO-0.6.3.tar.gz

cd RPi.GPIO-0.6.3

Start to build the C code
python3 setup build

cd RPi.GPIO-0.6.3/build/lib.linux-armv7l-3.4

Copy RPi module to virtual environment of python
cp RPi /home/pi/env/lib/python3.4/site-packages (which env is virtual environment)


Method 2:

source ~/env/bin/activate

Download RPi.GPIO 0.6.3

tar xvf RPi.GPIO-0.6.3.tar.gz

cd RPi.GPIO-0.6.3

Start to build the C code and install binary and library file into the virtual environment of python path.
python3 setup install

Reference:

2017年9月22日 星期五

2017年8月11日 星期五

[Python] Parse html by using python3

from html.parser import HTMLParser
from html.entities import name2codepoint

class MyHTMLParser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.anchors = []
        self.record = False


    def handle_starttag(self, tag, attrs):
        print("Start tag:", tag)
        for attr in attrs:
            print("     attr:", attr)
        if tag == "span":
            for k, v in attrs:
                if k == 'style' and v == 'color: #263645; font-weight: normal;' :
                    self.record = True
                    #self.anchors.append(v)
                    break

    def handle_endtag(self, tag):
        print("End tag  :", tag)

        if tag =="span":
            self.record = False

    def handle_data(self, data):
        print("Data     :", data)
        if self.record == True:
            self.anchors.append(data)

    def handle_comment(self, data):
        print("Comment  :", data)
    def handle_entityref(self, name):
        c = chr(name2codepoint[name])
        print("Named ent:", c)
    def handle_charref(self, name):
        if name.startswith('x'):
            c = chr(int(name[1:], 16))
        else:
            c = chr(int(name))
        print("Num ent  :", c)
    def handle_decl(self, data):
        print("Decl     :", data)


f = open("1.html")

p = MyHTMLParser()
p.feed(f.read())
p.close()

print (p.anchors)

Result

['Date', 'Scan Information']

Refernece:

2017年7月4日 星期二

[Python] How to create QRcode

Download python-qrcode library for github

Install dependent library “image”
pip install Image

Jump to python-qrcode

Create example.py under folder of python-qrcode.
Type two kind of code as following example.

import qrcode
img = qrcode.make('http://python.org')
img.show()

Advanced qrcode example

import qrcode
qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=10,
    border=4,
)
qr.add_data('Some data')
qr.make(fit=True)

img = qr.make_image()
img.show()

Reference:

2017年6月22日 星期四

[Python][Windows] How to use python on windows

  1. Install package
    PyQt5-5.6-gpl-Py3.5-Qt5.6.0-x64-2.exe
    python-3.5.2-amd64.exe

  2. Set the path of python into system environment
    Ref:
    [教學] 如何在 Windows 平台建立 Python 編程環境
    How to add to the pythonpath in windows 7?

  3. Copy ui to site-packages
    A. find out where is the location of site-packages
    Ref
    What is python’s site-packages directory?

  4. Install pyvisa through pip
    Through ez_setup.py to install pip
    Ref
    Windows 7 (or graphical install)
    According to above article, user cand download ez_setup.py from specific hyperlink.
    ez_setup.py



Jump to C:\Users\Administrator\AppData\Local\Programs\Python\Python35\Scripts


Type following command
Upgrade pip from pip-8.1.1 to pip-9.0.1
python -m pip install –upgrade pip


pip install pyvisa



Reference:

2017年6月19日 星期一

[RabbitVCS][Archlinux] How to use RabbitVCS in Archlinux

Download the package
rabbitvcs-0.16.tar.gz


Install pysvn package
Refer [Python] How to compile pysvn


Start rabbitvcs log function
~/rabbitvcs-0.16/rabbitvcs/ui
python2.7 log.py ~/workspace/trunk


Now easy to compare different version by rabbitvcs log function.


Reference:

2017年6月17日 星期六

[Python] How to compile pysvn

Download package
wget http://tigris.org/files/documents/1233/49465/pysvn-1.8.0.tar.gz


Decompress and jump into the folder
cd pysvn-1.8.0/Source


Start to configurate && compile
python2.7 setup.py configure
make


Under current folder will create a folder was called pysvn
cp -r pysvn /usr/lib/python2.7/site-packages/


Reference:

2017年6月14日 星期三

[Python] Compare two file by using python code

# Open file for reading in text mode (default mode)
f1  = open('/home/freeman/tftp/defalut_config.txt', 'r', errors='replace')
f2  = open('/home/freeman/tftp/NonVolValue.txt', 'r', errors='replace')


# Print confirmation
print("-----------------------------------")
print (f1)
print (f2)
print("-----------------------------------")

# Read the first line from the files
f1_line = f1.readline()
f2_line = f2.readline()

# Initialize counter for line number
line_no = 1

# Loop if either file1 or file2 has not reached EOF
while f1_line != '' or f2_line != '':

    # Strip the leading whitespaces
    f1_line = f1_line.rstrip()
    f2_line = f2_line.rstrip()

    # Compare the lines from both file
    if f1_line != f2_line:

        # If a line does not exist on file2 then mark the output with + sign
        if f2_line == '' and f1_line != '':
            print(">+", "Line-%d" % line_no, f1_line)
        # otherwise output the line on file1 and mark it with > sign
        elif f1_line != '':
            print(">", "Line-%d" % line_no, f1_line)

        # If a line does not exist on file1 then mark the output with + sign
        if f1_line == '' and f2_line != '':
            print("<+", "Line-%d" % line_no, f2_line)
        # otherwise output the line on file2 and mark it with < sign
        elif f2_line != '':
            print("<", "Line-%d" %  line_no, f2_line)

        # Print a blank line
        print()

    #Read the next line from the file
    f1_line = f1.readline()
    f2_line = f2.readline()


    #Increment line counter
    line_no += 1

# Close the files
f1.close()
f2.close()


Reference:

2017年5月31日 星期三

[python] Using code to understand watch more clearly


The following example program will monitor the current directory recursively for file system changes and simply log them to the console:

import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s - %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')
    path = sys.argv[1] if len(sys.argv) > 1 else '.'
    event_handler = LoggingEventHandler()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()


Reference:

2017年5月23日 星期二

2017年5月18日 星期四

[Python] How to use pyqt5

Install qt package. This will install all package about qt5.
sudo pacman -S qt

Using designer to design py UI
/usr/bin/designer

Using pyuic5 to convert UI to python code
pyuic5 main.ui -o main.py

Install pyqt5 library package, so when execute python code will show UI properly.
sudo pacman -S python-pyqt5

2017年5月11日 星期四

2016年5月12日 星期四

2016年2月25日 星期四

[Yocto][Python] How to install pysqlite

tar xvf pysqlite-2.8.1.tar
cd pysqlite-2.8.1
python setup.py install

Reference:
pysqlite 2.8.1

Q:
In file included from src/module.c:24:
src/connection.h:33:21: error: sqlite3.h: No such file or directory
In file included from src/module.c:24:
src/connection.h:38: error: expected specifier-qualifier-list before ‘sqlite3’
In file included from src/module.c:25:
src/statement.h:37: error: expected specifier-qualifier-list before ‘sqlite3’
src/module.c: In function ‘module_complete’:
src/module.c:101: warning: implicit declaration of function ‘sqlite3_complete’
src/module.c: In function ‘init_sqlite’:
src/module.c:400: warning: implicit declaration of function ‘sqlite3_libversion’
src/module.c:400: warning: passing argument 1 of ‘PyString_FromString’ makes pointer from integer without a cast
/usr/local/include/python2.7/stringobject.h:63: note: expected ‘const char *’ but argument is of type ‘int’
error: command 'gcc' failed with exit status 1
A:
sudo apt-get install libsqlite3-dev

Reference:
How to install pysqlite?

root@freeman-laptop:/home/freeman/sdk2_er5/yocto_meta_2.0.0.5/build# python -c 'import pysqlite2'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ImportError: No module named pysqlite2

After install pysqlite 2.8.1 will no display error message again.

root@freeman-laptop:/home/freeman/sdk2_er5/yocto_meta_2.0.0.5/build# python -c 'import pysqlite2'

2015年6月21日 星期日

[Python] How to install python package (BeautifulSoup4)

1. Install python tool for installing python package.
sudo pacman -S python-pip
sudo pacman -S python2-pip (This pip is for python2)

2. Install python package by using pip.
sudo pip install BeautifulSoup4
Reference:
  1. [source code] Python Programming Tutorial - 25 - How to Make a Web Crawler
  2. How to Build a Web Crawler (1/3)
  3. python from scratch

2013年9月18日 星期三

[python] ping6 to Ipv6


[python] ping6 to Ipv6
#coding:utf8
import os
import threading
import Queue
queue = Queue.Queue()
address = ['2001:730:1f:462::2'] # 2001:730:1f:462::2 = CNR
_thread = 1
for ip in address:
queue.put(ip) #将IP放入队列中。函数中使用q.get(ip)获取

def check(i,q):
while True:
ip=q.get() #获取Queue队列传过来的ip,队列使用队列实例queue.put(ip)传入ip,通过q.get() 获得
print "Thread %s:Pinging %s" %(i,ip)
data = os.system("ping6 -c 1 %s > /dev/null 2>&1" % ip)#使用os.system返回值判断是否正常
if data==0:
print "%s:正常运行" % ip
else:
print "%s:停止工作" % ip
q.task_done() #表示queue.join()已完成队列中提取元组数据

for i in range(_thread):#线程开始工作
run=threading.Thread(target=check,args=(i,queue)) #创建一个threading.Thread()的实例,给它一个函数和函数的参数
run.setDaemon(True)#这个True是为worker.start设置的,如果没有设置的话会挂起的,因为check是使用循环实现的
run.start() #开始线程的工作
queue.join()#线程队列执行关闭
print "ping 工作已完成"

Reference :