Milind Deore
Milind Deore

Reputation: 3063

AttributeError due to sys.argv[0] for 'import tensorflow as tf' inside c

I have embedded python2.7/python3.4m code inside c file running on Ubuntu14.4. The python code is imports tensorflow, when it fails.

#include <stdio.h>
#include <Python.h>

int
main(int argc, char *argv[])
{
  Py_SetProgramName(argv[0]);  /* optional but recommended */
  Py_Initialize();
  PyRun_SimpleString("import tensorflow as tf");
  Py_Finalize();
  return 0;
} 

This gives following output:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/__init__.py", line 100, in <module>
    from tensorflow.python.platform import app
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/platform/app.py", line 23, in <module>
    from tensorflow.python.platform import flags
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/platform/flags.py", line 25, in <module>
    _global_parser = _argparse.ArgumentParser()
  File "/usr/lib/python2.7/argparse.py", line 1575, in __init__
    prog = _os.path.basename(_sys.argv[0])
AttributeError: 'module' object has no attribute 'argv'

Any help in this would be greatly appreciated. I compiled it useing cmake as well as bazel.

This problem is happening even inside virtualenv installation.

Upvotes: 0

Views: 1450

Answers (2)

colin-zhou
colin-zhou

Reputation: 185

I found the old version (1.4.0) exist this error, but not included the new version (like tensorflow == 1.13.1), if you could update the tensorflow to the latest version, that may be a better solution.

Upvotes: 0

Milind Deore
Milind Deore

Reputation: 3063

I am so stupid! well this works, as tensorflow needs sys.argv.

int
main(int argc, char *argv[])
{
  Py_SetProgramName(argv[0]);  /* optional but recommended */
  Py_Initialize();
  PyRun_SimpleString("import sys\n"
                     "sys.argv = ['']");
  PyRun_SimpleString("import tensorflow as tf");
  Py_Finalize();
  return 0;
} 

Upvotes: 4

Related Questions