Thanks to visit codestin.com
Credit goes to github.com

Skip to content

PythonEngine.Exec scope between classes #591

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
evandavey opened this issue Dec 30, 2017 · 3 comments
Closed

PythonEngine.Exec scope between classes #591

evandavey opened this issue Dec 30, 2017 · 3 comments

Comments

@evandavey
Copy link

Environment

  • Pythonnet version: 2.3.0
  • Python version: 3.6
  • Operating System: Windows 10

Details

I am embedding Python using PythonEngine.Exec to run code read from a file which seems to be losing global scope.

string code;
using (var streamReader = new StreamReader(scriptFile, Encoding.UTF8)) {
   code = streamReader.ReadToEnd();
}
 
using (Py.GIL()) {
    PythonEngine.Exec(code)
}

The python code contains two classes:

class Test1():
   pass

class Test2():
   def __init__(self):
       Test1()

Test2()

Error:

NameError: name 'Test1' is not defined
yagweb added a commit to yagweb/pythonnet that referenced this issue Jan 10, 2018
yagweb added a commit to yagweb/pythonnet that referenced this issue Jan 10, 2018
@yagweb
Copy link
Contributor

yagweb commented Jan 10, 2018

It's a bug of the Exec method. I just submit a PR to fix it.

Another method is using the PyScope class,

string code;
using (var streamReader = new StreamReader(scriptFile, Encoding.UTF8)) {
   code = streamReader.ReadToEnd();
}
 
using (Py.GIL()) {
    var scope = Py.CreateScope();
    scope.Exec(code);
    var t1 = (scope as dynamic).Test1();
    var t2 = scope.Get<dynamic>("Test2")();
}

@evandavey
Copy link
Author

Thanks. I also had some success using PythonEngine.ModuleFromString(...).

den-run-ai added a commit that referenced this issue Jan 11, 2018
@den-run-ai
Copy link
Contributor

@evandavey @yagweb thanks for this bug report and pull request!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants