IronPython disable Import after use
Is there any way to disable the use of import once I've finished using it? I'm using IronP开发者_如何学运维ython as a scripting engine and I don't want users to be able to import anything. This could be done in LuaInterface by the use of setfenv:
luanet.load_assembly("System.Windows.Forms")
luanet.load_assembly("System.Drawing")
Form=luanet.import_type("System.Windows.Forms.Form")
-- Only allow the use of the form class
local env = { Form = _G.Form }
setfenv(1, env)
Or by setting the import functions to nil before parsing the script file:
luanet.load_assembly = nil
luanet.import_type = nil
Is this possible in IronPython?
One option is to pre-check the scripts you are executing and disallow any that have import
statements (or from ... import
statements).
foreach(line in script) {
if(line.TrimeStart().StartsWith("import") || line.TrimeStart().StartsWith("from") {
throw ...;
}
}
It's not foolproof (__import__
is still an issue), but it will cover the vast majority of cases.
You can create a hook to the import function and deal with user import anyway you like.
In you case you can just return null for any import that your hook gets.
It was explained how to do it here: https://stackoverflow.com/a/4127766/448547
精彩评论