0

I'm working on embedded python. However I have a trouble in work.

I used 'PyImport_ImportModule' function because I wanted to import python module in C++. Example,

# foo.py

class foo:
    def test(self):
        print("foo.test")


foo().test()

// main.cpp
void main()
{
    PyObject* myModule = PyImport_ImportModule("foo");
    if (myModule)
    {
        PyObject* func = PyObject_GetAttrString(myModule, "test");
        PyObject_CallObject(func, nullptr);
    }
}

When i run this main.cpp code, output is not expected result that i thought.

I thought this code result is ,

**console**
>> foo.test

but actual result is,

**console**
>> foo.test
>> foo.test

I think the reason foo.test is called twice is because the 'PyImport_ImportModule' function runs the script. So i wonder how to invoke python function in c++ without running scirt.

Aamir
  • 1,974
  • 1
  • 14
  • 18
happy_S
  • 3
  • 2

1 Answers1

1

Importing a module is the same as "running the script" in Python. All statements are run top-to-bottom, functions, classes are created when their definitions are executed, on the fly.

If a module should be used both as a standalone script and as imported module, the canonical way how to do this in Python is wrapping in "ifmain" block

# foo.py

class foo:
    def test(self):
        print("foo.test")

if __main__ == "__main__":
    foo().test()
Quimby
  • 17,735
  • 4
  • 35
  • 55