问题:在python文件中引用自己创建的文件时报错:ImportError: No module named mantutu.com
解决:包的名称不能包含点(.)
方法:
将文件名由mantutu.com改为mantutu就可以了
引用:from mantutu import getarticles
注:如果引入一个文件夹下文件时,就需要在文件下touch __init__.py
分类 "Python" 下的文章
问题:python程序定时执行任务
解决:使用sleep或threading或sched实现
方法:
一、使用循环sleep,缺点:阻塞
def timer(n):
'''
每n秒执行一次
'''
while True:
print time.strftime('%Y-%m-%d %X',time.localtime())
yourTask() # 此处为要执行的任务
time.sleep(n)
二、使用threading的Timer,非阻塞
def printHello():
print "Hello World"
t = Timer(2, printHello)
t.start()
if name == "__main__":
printHello()
三、使用sched方法,延时高度,非阻塞
-- coding:utf-8 --
use sched to timing
import time
import os
import sched
初始化sched模块的scheduler类
第一个参数是一个可以返回时间戳的函数,第二个参数可以在定时未到达之前阻塞。
schedule = sched.scheduler(time.time, time.sleep)
被周期性调度触发的函数
def execute_command(cmd, inc):
'''
终端上显示当前计算机的连接情况
'''
os.system(cmd)
schedule.enter(inc, 0, execute_command, (cmd, inc))
def main(cmd, inc=60):
enter四个参数分别为:间隔事件、优先级(用于同时间到达的两个事件同时执行时定序)、被调用触发的函数,
给该触发函数的参数(tuple形式)
schedule.enter(0, 0, execute_command, (cmd, inc))
schedule.run()
每60秒查看下网络连接情况
if name == '__main__':
main("netstat -an", 60)
问题:python如何对打开的文件进行增加内容,而不是覆盖
解决:打开文件时使用追加方式(a)打开
方法:
afile = open('a.txt', 'a')
afile.write('hello
')
afile.close()
注:r:读文件,w:写文件,a:文件追加内容
参考:http://www.cnblogs.com/xinchrome/p/5011304.html
问题:使用pyvenv .venv时报错-bash: pyvenv: command not found
解决:虽然ubuntu16.04默认安装了python3.5.2,但是没有pyvenv方法,所以仍需要安装python3.5.1,安装方法见http://it.xiaomantu.com/web/linux/186.html
方法:
安装python3.5.1
问题:python如何往列表前面插入数据
解决:因为python没有prepend方法,只有append方法,所以可以使用insert方法实现prepend
方法:
a = [1,2,3,4,5]
a.append(6) ==> [1,2,3,4,5,6]
a.insert(0, 7) ==> [7,1,2,3,4,5,6]
a = [8] + a ==> [8,7,1,2,3,4,5,6]