问题描述
这可能不是IronPython的特别问题,所以那里的Python开发人员可能可以提供帮助.
This may not specifically be an IronPython question, so a Python dev out there might be able to assist.
我想使用IronPython在.Net桌面应用程序中运行python脚本,并希望为用户提供强制终止脚本的功能.这是我的测试脚本(我是Python的新手,所以可能并不完全正确):-
I want to run python scripts in my .Net desktop app using IronPython, and would like to give users the ability to forcibly terminate a script. Here's my test script (I'm new to Python so it might not be totally correct):-
import atexit
import time
import sys
@atexit.register
def cleanup():
print 'doing cleanup/termination code'
sys.exit()
for i in range(100):
print 'doing something'
time.sleep(1)
(请注意,我可能想在某些脚本中指定一个"atexit"函数,使它们可以在正常或强制终止期间执行任何清除操作.)
(Note that I might want to specify an "atexit" function in some scripts, allowing them to perform any cleanup during normal or forced termination).
在我的.Net代码中,我使用以下代码来终止脚本:
In my .Net code I'm using the following code to terminate the script:
_engine.Runtime.Shutdown();
这将导致调用脚本的atexit
函数,但脚本实际上并未终止-for
循环继续进行.其他几篇SO文章(在此处和)说sys.exit()
应该可以解决问题,那么我想念的是什么?
This results in the script's atexit
function being called, but the script doesn't actually terminate - the for
loop keeps going. A couple of other SO articles (here and here) say that sys.exit()
should do the trick, so what am I missing?
推荐答案
似乎无法终止正在运行的脚本-至少不能以友好"的方式终止.我见过的一种方法是在另一个线程中运行IronPython引擎,并在需要停止脚本时中止线程.
It seems that it's not possible to terminate a running script - at least not in a "friendly" way. One approach I've seen is to run the IronPython engine in another thread, and abort the thread if you need to stop the script.
我并不热衷于这种暴力破解方法,因为这样做可能会使脚本使用的任何资源(例如文件)处于打开状态.
I wasn't keen on this brute-force approach, which would risk leaving any resources used by the script (e.g. files) open.
最后,我创建一个C#帮助器类,如下所示:-
In the end, I create a C# helper class like this:-
public class HostFunctions
{
public bool AbortScript { get; set; }
// Other properties and functions that I want to expose to the script...
}
当托管应用程序想要终止脚本时,它将AbortScript
设置为true.该对象通过范围传递给正在运行的脚本:-
When the hosting application wants to terminate the script it sets AbortScript
to true. This object is passed to the running script via the scope:-
_hostFunctions = new HostFunctions();
_scriptScope = _engine.CreateScope();
_scriptScope.SetVariable("HostFunctions", _hostFunctions);
在我的脚本中,我只需要策略性地进行检查以查看是否已请求中止,并进行适当的处理,例如:-
In my scripts I just need to strategically place checks to see if an abort has been requested, and deal with it appropriately, e.g.:-
for i in range(100):
print 'doing something'
time.sleep(1)
if HostFunctions.AbortScript:
cleanup()
这篇关于终止IronPython脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!