質問

I have an IronPython application that does processing of records for exclusion rules. Essentially, I have a directory structure as such:

Lib\

Lib\DBCL\General.py

Lib\Exclusions\script.py

My program creates an instance of the IronPython runtime:

Dictionary<String, Object> oDic = new Dictionary<String, Object>();
oDic.Add("Debug", true);
iEngine = Python.CreateEngine(oDic);
iScope = iEngine.CreateScope(new Dictionary<String, Object> { { "sql", iSql } });
iScriptSource = aScript;
iSource = iEngine.CreateScriptSourceFromFile(iScriptSource);

iSql is a C# class for SQL interaction (just for the record). iScriptSource, in this case, is the python script: "Lib\Exclusions\script.py"

Now, inside my IronPython script, I import the DBCL folder and the General file:

import DBCL
from DBCL import General

So, I execute script.py:

iSource.Execute(iScope); // Edited 1/10/2014 to show I am passing the scope in.

Inside my script.py file, I make a call to General.py to perform a lookup in SQL (remember, I have added a variable called "sql" via iEngine.CreateScope()).

However, IronPython says that that global variable doesn't exist. But if I make the call in script.py, it exists as a global variable. How can I make my variables globally available to all scripts that I import?

If there is any confusion or if this question is poorly formed, please let me know and I'll try and fix it. I feel there's something simple I'm missing, but right now it's temporarily solved by simply passing "sql" around via arguments. I'd like to avoid that if possible, but if I can't then it's okay.

役に立ちましたか?

解決

Please, check Using global variables in a function other than the one that created them, third answer. In short, the global variables in python are module scoped, not interpreter scoped.

I suspect in your case in script.py you need

import DBCL
from DBCL import General
General.sql = sql

他のヒント

Try passing the scope you created when executing the script:

iSource.Execute(iScope);

That should automatically inject anything in the scope into the script's global namespace.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top