个人备忘,仅供参考
格式化输出
基础用法
a = 3.232421 # float type
print(f"a = {a}")
# Out: a = 3.232421
对齐与填充占长
基本结构
print(f"a = {a:x>8}")
[变量名] : [填充字符] [对齐方向] [长度]
填充字符:可为空,默认为空格。
对齐方向:< 、 ^、 >分别代表左对齐、居中、右对齐
长度:总长度
Example:
a = 3.21 # float type
print(f"a = {a:>8}")
# Out: a = 3.21
a = 3.21 # right align
print(f"a = {a:x>8}") # right align, with 'x' paded in
# Out: a = xxxx3.21
a = 3.21 # float type
print(f"a = {a:^8}")
# Out: a = xx3.21xx
print(f’{mx:>10.3f} {my:>10.3f} {mz:>10.3f}')
精度与宽度
基本结构
print(f"a = {a:10.3f}")
[变量名] : [字符长度] [小数点精度]
a = 3.21 # float type
print(f"a = {a:10.3f}")
# a = 3.210
结合一下之前的填充和对齐,可以做出这样的效果:
a = 3.21 # float type
print(f"a = {a:j<10.3f}") # total len: 10, pad: 'j', precision:3, left align
# a = 3.210jjjjj
最后一个字符f代表的是浮点数。需要了解的朋友参考一下c语言。一般来说,不用关心。
import相关
模块导入
import time
import sys
# etc
导入本地不同aaa.py文件也是一样的步骤:
import aaa # ./aaa.py
如果不在相同目录,则需要加入如下步骤:
import sys
sys.path.append("abc/")
import aaa # ./abc/aaa.py
# another example
import sys
sys.path.append("../")
import aaa # ../aaa.py
模块使用
import aaa
ret = aaa.foo()
这个其实挺简单的。但我每次都会忘记加包名
pickle相关
导出到文件
import pickle
with open('filename', 'wb') as f:
pickle.dump(data_to_dump, f) # data can be any type
从文件导入
import pickle
with open('filename', 'wb') as f:
ret = pickle.load(f)
多线程子线程参考写法
subThread.py
import trace
import threading
import time
class traceThread(threading.Thread):
def __init__(self, name, etc):
super().__init__()
self.killed = False
def start(self):
self.__run_backup = self.run
self.run = self.__run
threading.Thread.start(self)
def __run(self):
sys.settrace(self.globaltrace)
self.__run_backup()
self.run = self.__run_backup
def globaltrace(self, frame, event, arg):
if event == 'call':
return self.localtrace
else:
return None
def localtrace(self, frame, event, arg):
if self.killed:
if event == 'line':
raise SystemExit()
return self.localtrace
def kill(self):
self.killed = True
def func(self):
while True:
print('thread running')
注意使用的时候,target需要指定,而不能是默认的run()。即:
t1 = traceThread(target = func)
如果对即时性要求不高,或需要本轮循环必须完成,也可以参考下面的写法:
PS: 这个也提供诸如pause、resume的方法。
class subThread(threading.Thread):
def __init__(self, name, etc):
super().__init__()
self.__alive = threading.Event()
self.__running = threading.Event()
self.__alive.set()
self.__running.set()
def run(self):
while self.__alive.isSet():
self.__running.wait() # return immitatly when True
# Act like While 1
#Set init value like n = 1
#Running
#clear this loop, like n += 1
def stop(self):
self.__alive.clear()
self.__running.set()
#other clearance, like fclose()
def pause(self):
self.__running.clear()
def resume(self):
self.__running.set()
暂时先这样,想到了会增加。欢迎各位补充。