python脚本的后台执行
一般而言, 在windows中执行python脚本, 需要打开命令行,然后执行
python target.py
要提高自动化程度, 可以:
- 创建当前程序的快捷方式, 在属性-目标项的前端插入python
- 更改默认打开方式为使用中的python.exe或在打开方式中选取
使用python打开程序时, 会绑定显示命令提示符窗口,参考这个解决:
- 将python.exe替换成pythonw.exe, 程序就可以在Windows后台执行, 不显示命令提示符窗口;
- 另一种方法是修改脚本的扩展名为".pyw",双击即可后台运行,不需要修改任何代码
ipython脚本的执行
以下内容选自ipython官方wiki:
%run -i foo.py 将在执行py文件后保留变量在当前ipython console, 会占用ipython程序
%bg _ip.magic('run -i foo.py') 程序将在后台运行, 同时你可以实时访问其中的变量,即使时在运行中
threading
threading的基本用法:
def func():
# Do something here
threading.Thread(target=func).start()
threading与定时器结合示例
import threading
def producer_time(next_coroutine=None,max_iter=10, dt=2):
counter = 0
status = True
while(True):
t = time.time()
if (not status) and t%dt<0.1:
# next_coroutine.send('run') # 这里可以传进参数, 虽然这里没有必要; 这说明其仍有额外的自由度
print(t)
counter+=1
status = True
if (status and t%dt>=0.1):
status = False #reset
if counter>max_iter:
break
threading.Thread(target=producer_time).start()
print('a')
一些观测到的特性:
- Ctrl+C 不会终止threading中的程序
- Ctrl+C 之后虽然控制台出现了In提示符, 但threading终止之前依然无法执行新的程序
在搜索threading用法的过程中, 发现了诸多可能有用的库,包括:
- subprocess
- signal
- multiprocessing
- ayncio
- concurrent等
以及一些不错的网站/教程:
将在日后作进一步的探索