ironpython停止更新,终止IronPython脚本

This may not specifically be an IronPython question, so a Python dev out there might be able to assist.

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)

(Note that I might want to specify an "atexit" function in some scripts, allowing them to perform any cleanup during normal or forced termination).

In my .Net code I'm using the following code to terminate the script:

_engine.Runtime.Shutdown();

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?

解决方案

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.

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...

}

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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值