由于sys.argv [0]引起的AttributeError导入张量流为tf'在c

时间:2016-12-25 18:32:18

标签: python c tensorflow

我在Ubuntu14.4上运行的c文件中嵌入了python2.7 / python3.4m代码。 python代码是导入tensorflow,当它失败时。

#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;
} 

这给出了以下输出:

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'

非常感谢任何帮助。我编译它使用cmake和bazel。

即使在virtualenv安装中也会发生此问题。

2 个答案:

答案 0 :(得分:4)

我是如此愚蠢!这很有用,因为tensorflow需要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;
} 

答案 1 :(得分:0)

我发现旧版本(1.4.0)存在此错误,但未包括新版本(如tensorflow == 1.13.1),如果您可以将tensorflow更新为最新版本,则可能是更好的解决方案。