Skip to content Skip to sidebar Skip to footer

Pass Argument To Pyrun_file(***)

I am writing some code in C and in Python. I have a python file called sample.py which accepts two string parameters. My C program calls the python function using the PyRun_SimpleS

Solution 1:

To set arguments do like the following code:

wchar_t** wargv = newwchar_t*[argc];
for(int i = 0; i < argc; i++)
{
    wargv[i] = Py_DecodeLocale(argv[i], nullptr);
    if(wargv[i] == nullptr)
    {
        return EXIT_FAILURE;
    }
}

Py_Initialize();

// char* py=...PySys_SetArgv(argc, wargv);
PyRun_SimpleString(py);

Py_Finalize();

for(int i = 0; i < argc; i++)
{
    PyMem_RawFree(wargv[i]);
    wargv[i] = nullptr;
}

delete[] wargv;
wargv = nullptr;

Solution 2:

Use PyRun_String. It has a signature similar to PyRun_File:

PyObject* PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals)

Update:

In your case, it whould be simple enough to just copy the command line arguments into the string you want to execute, just like you tried in your question. Your code won't work though, because that's not how you concatenate strings in C. Try this instead:

#include<Python.h>#include<stdio.h>#include<string.h>intmain(int argc, char **argv){
    char py[1000]; /* that should be big enough */strcpy(py, "import sample\nsample.mainfunc(");
    strcat(py, argv[1]);
    strcat(py, ",'Isolated_domU_t')\n");

    Py_Initialize();
    PyRun_SimpleString(py);
    Py_Finalize();
}

This is, of course, only the quick&dirty version without checking if there even is an argument passed to the program, or checking for its length.

Solution 3:

can use the snprintf or like his function and type this

char haies1[2048];
snprintf(haies1, sizeof(haies1),"import sample\n"
                "sample.mainfunc("%s",'Isolated_domU_t')\n",argv[1])

then can use the PyRun_SimpleString function like this

Py_Initialize();
PyRun_SimpleString(haies1);
Py_Finalize();

Post a Comment for "Pass Argument To Pyrun_file(***)"