1

I have a python script which is invoked inside a C++ application. When I import matplotlib I get the following error.

List index out of range.

In my script the only matplotlibrelated code is

import matplotlib.pyplot as plt
f = plt.figure()

When I invoke the script on its own it works. I get this exception only when it is embedded in a C++ Program. Do I need to provide some extra dependencies when the script uses matplotlib?

When I comment out the matplotlibfunctions I don't get the exception

Update

The C++ Code is from the python docs link : 1.3. Pure Embedding

I haven't modified anything from the C++ code. It works as long as there are no matplotlib related code.

abhilb
  • 5,639
  • 2
  • 20
  • 26

1 Answers1

1

The reason is that the backend used by matplotlib is tk in my case. The window initialization of the tk has this code in there

baseName = os.path.basename(sys.argv[0]) 

And in my case the argv is empty and that is the reason for list index out of range error.

One work around I found here. We can passing dummy values like this:

    wchar_t const *dummy_args[] = { L"Python", NULL };  // const is needed because literals must not be modified
    wchar_t const **argv = dummy_args;
    int             argc = sizeof(dummy_args) / sizeof(dummy_args[0]) - 1;
    PySys_SetArgv(argc, const_cast<wchar_t **>(argv));
abhilb
  • 5,639
  • 2
  • 20
  • 26