Dor*_*tuh 5 python subprocess python-2.7
我目前有一种方法可以通过使用子进程调用来执行其他 python 脚本,我想知道是否有任何时间可以完成此操作?脚本在一个间隔内运行,我想从中实现的是检查脚本是否在该间隔内完成。
def execute_scripts(script_name):
process = sp.Popen(['python2.7', script_name])
print 'executing - ' + script_name
Run Code Online (Sandbox Code Playgroud)
使用timeit来计时小段代码的执行。
#sleep2.py
import time
time.sleep(2)
Run Code Online (Sandbox Code Playgroud)
您需要使用subprocess.call进行阻塞,直到调用完成。
import timeit
import subprocess as sp
def execute_scripts(script_name):
process = sp.call(['python2.7', script_name])
print 'executing - ' + script_name
t = timeit.Timer("execute_scripts('sleep2.py')", setup="from __main__ import execute_scripts")
print 'time taken : %f seconds' % t.timeit(1)
executing - sleep2.py
time taken : 2.032273 seconds
Run Code Online (Sandbox Code Playgroud)
或者,您可以通过编写装饰器来计时任何函数调用来概括这一点
import time
import subprocess as sp
def timed_execution(function):
def wrapper(arg):
t1 = time.time()
function(arg)
t2 = time.time()
return 'time taken : %f seconds' % (t2 - t1) + "\n"
return wrapper
@timed_execution
def execute_scripts(script_name):
sp.call(['python2.7', script_name])
print 'executing - ' + script_name
print execute_scripts('sleep2.py')
executing - sleep2.py
time taken : 2.025291 seconds
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1343 次 |
最近记录: |