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

10,036

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.

Share:
10,036
Chengy
Author by

Chengy

Updated on June 15, 2022

Comments

  • Chengy
    Chengy almost 2 years

    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?