“AttributeError: 'module' object has no attribute 'argv'” when using Python.h

拈花ヽ惹草 提交于 2019-12-06 19:16:41

问题


When messing around with Python.h I got this error:

AttributeError: 'module' object has no attribute 'argv'

C++ code:

#include "stdafx.h"  
#include "C:/Python27/include/Python.h"  
#include <iostream>  

using namespace std;  


int main()  
{
    Py_Initialize();
    PyRun_SimpleString("import sys\nprint sys.argv[0]");
}

Which in Python is:

import sys
print sys.argv[0]

What am I missing?


回答1:


Conceptually, sys.argv should contain the arguments that Python was called with (and what it was called under). What should it have if it were called like this, though?

You can load the calling program's argv into sys, if you want:

int main(int argc, char **argv)
{
    Py_Initialize();
    PySys_SetArgv(argc, argv);
    PyRun_SimpleString("import sys\nprint sys.argv");
}

gives

localhost-2:argv $ ./a.out
['./a.out']
localhost-2:argv $ ./a.out arg0 17
['./a.out', 'arg0', '17']

See also Py_SetProgramName.



来源:https://stackoverflow.com/questions/12230210/attributeerror-module-object-has-no-attribute-argv-when-using-python-h

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!