Giter VIP home page Giter VIP logo

python's Introduction

test

python's People

Contributors

kif1205 avatar

python's Issues

Class

class Calculator:

name = 'My Calculator'

def add(self , x , y):
    return cal('%s+%s'%(x,y))
def minus(self , x , y):
    return cal('%s-%s'%(x,y))
def times(self , x , y):
    return cal('%s*%s'%(x,y))
def divide(self , x , y):
    return cal('%s/%s'%(x,y))

def cal(calcul_string):
return eval(calcul_string)

calcul = Calculator()
print(calcul.name)
print(calcul.add(1,2))
print(calcul.minus(1,2))
print(calcul.times(1,2))
print(calcul.divide(1,2))

#excution result
'''
C:\Python34>python.exe example_class.py
My Calculator
3
-1
2
0.5
'''

Python - Socket

Summary :
Study Socket and write some example here


What to do :

  • Sudy Socket
  • Write some examples

itertools.permutations

print([x for x in itertools.permutations('1234')])

[('1', '2', '3', '4'), ('1', '2', '4', '3'), ('1', '3', '2', '4') ... ]

Python - Basic Command

Summary :
Collect all the Python Basic Commands by studying


What to do :

  • List the command and summary

檔案處理

###############

Open a file

###############

text = 'This is my first test.\nThis is next line.\nThis is last line'

my_file = open('my_file.txt','w') #write
my_file.write(text)
my_file.close()

#################

Append a file

#################

append_text = '\nThis is appended file.'

my_file = open('my_file.txt','a') #append
my_file.write(append_text)
my_file.close()

###################

Read a txt file

###################

file = open('my_file.txt','r')
content=file.read()
print('#############################\n')
print('The resule of file.read()')
print(content)

content=file.readlines()
print('#############################\n')
print('The resule of file.readlines() without opening file')
print(content)

file = open('my_file.txt','r')
content=file.readlines()
print('#############################\n')
print('The resule of file.readlines()')
print(content)

file = open('my_file.txt','r')
content=file.readline()
content_second=file.readline()
print('#############################\n')
print('The resule of file.readline()')
print(content,content_second)

The solutions to delete a locked thread

import threading
import time

thread_join_time = 5
word = []

def run():
global stop_threads
stop_threads = False
print('thread running')
global word

time.sleep(thread_join_time+1) # This time value should large than thread_join_time
print("len(word) is :"+str(len(word)))
if len(word)>0:        
    for i in word:
        time.sleep(1)            
        print("################"+i)
        print(stop_threads)
        if stop_threads: 
            print("@@@@@@@@@@@@@@@@@@@@@@@@@@")
            print(stop_threads)
            return
    return
else:
    print("### No data , thus kill the current thread ###")
    threading.current_thread()._delete()
    print("### No data , thus kill the current thread ###")

def thread_test():
t1 = threading.Thread(target = run)
t1.start()
t1.join(thread_join_time)
global word
word = ["5","4"]

def thread_stop():
print('thread killed stop_threads=True')
global stop_threads
stop_threads=True
time.sleep(1)

def test():
print(threading.active_count())
print(threading.enumerate())
time.sleep(1)

# Linux solution to set a timeout value for a function execution
#try:
#    with timeout(5, exception=RuntimeError):
#        while True:
#            thread_test()
#except RuntimeError:
#    pass
#	



thread_test()


# Flag solution to set a flag to quit the locked thread   
#thread_stop()

print(threading.active_count()) 
print(threading.enumerate())

test()

Input

while True:
print("1.test_1\n2.test_2\nothers for leaving")
a_input = input("Please givea number :") # return a string
if a_input == '1':
print("This test is ",a_input)
elif a_input == '2':
print("This test is ",a_input)
else:
break

Change linux Date function

def tc_Misc_00005():
case = ["test"]
SYS_SetTestCaseName(case)

Test_Day_Count = 3

print_log("Current Date is : " + SSH_Write("date")[0])
Current_Year = SSH_Write("date +%Y")[0][:-1]
Current_Month = SSH_Write("date +%m")[0][:-1]
Current_Day = SSH_Write("date +%d")[0][:-1]

if len(Current_Month) == 1:
    Current_Month = "0" + Current_Month

Test_Days = str(int(Current_Day) + Test_Day_Count)
if len(Test_Days) == 1:
    Test_Days = "0" + str(Test_Days)	

SSH_Write("date " + Current_Month + Test_Days + "1200" + Current_Year)

print_log("Current Date is : " + SSH_Write("date")[0])

Python PIP 安装模块报ascii码错误的问题

Python PIP 安装模块报ascii码错误的问题
January 27, 2016
在Windows10与Python2.7及PIP环境下安装模块总是报编码错误,如下:

UnicodeEncodeError: 'ascii' codec can't encode character u'\u258e' in position 8: ordinal not in range(128)
这个问题的产生可能是用户的语言环境默认的编码设置所致,在网上找到解决办法,在python2.7\Lib\site-packages目录下新建一个sitecustomize.py 文件,插入代码如下:

import sys
sys.setdefaultencoding('UTF-8')
再尝试安装模块就可以通过。

If/Elif/Else

def Who_is_bigger(x,y,z):
if x>y:
print("x>y")
elif x>z:
print("xz")
else:
print("x<y and x<z")

Who_is_bigger(4,2,3)

sed examples

sed -i 's/"LogEFIStatusCodes": "[A-z|0-9|:punct:|.| ]*"/"LogEFIStatusCodes": "Error code"/' /etc/bios_current.json

Global變數

apple=100
a = None
def fun():
a = 20
return a+100

print(apple)
print('apast=',a)
print(fun())
print('a now=',a)

def fun2():
global a
a = 20
return a+100

print(apple)
print('apast=',a)
print(fun2())
print('a now=',a)

Python dictionary get() Method

https://www.tutorialspoint.com/python/dictionary_get.htm

Description
The method get() returns a value for the given key. If key is not available then returns default value None.

Syntax
Following is the syntax for get() method −

dict.get(key, default=None)
Parameters
key -- This is the Key to be searched in the dictionary.

default -- This is the Value to be returned in case key does not exist.

Return Value
This method return a value for the given key. If key is not available, then returns default value None.

Example
The following example shows the usage of get() method.

#!/usr/bin/python

dict = {'Name': 'Zabra', 'Age': 7}

print "Value : %s" % dict.get('Age')
print "Value : %s" % dict.get('Education', "Never")
When we run above program, it produces following result −

Value : 7
Value : Never

Python 程式裡的 __name__ 可以用來分辨程式是直接執行還是被 import 的

剛開始寫 python 的時候,看到幾乎每個程式的最後面都有一段 code:

if name == 'main':
doSomething()

一直都不懂那是什麼意思,只知道要照抄然後執行程式時那段就會被執行。後來深入研究之後才比較瞭解 name 的意思了。

原來如果一個 python script 是被別的 python script 當成 module 來 import 的話,那麼這個被 import 的 python script 的 name 就會是那個 python script 的名稱。而如果這個 python script 是直接被執行的話,name 就會是 main

舉例來說,如果我有一個程式叫做 myModule.py,內容就是一行顯示自己的 name:

print 'name:' + name

那麼我直接執行它的話,結果會顯示 main:

bash-3.2$ python myModule.py
name:main

但如果我準備了另一個程式叫做 testModule.py,裡面就這麼一行去 import myModule:

import myModule

然後我去執行 testModule.py 的話,則會顯示 myModule:

bash-3.2$ python testModule.py
name:myModule

所以用 name 就可以分辨我的程式是被 import 當成模組還是被直接執行的。這樣附帶的好處就是如果我寫的程式平常可以被 import 來使用,但有時它自己也可以直接執行。其它語言的話,可能就要區分 library 跟使用 library 的程式,而 python 的話這兩者的界線就很模糊。

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.