Up

Run Python Script from C/C++ Program

Calling a command from Python Script

 

Command Python is called by C function system.

 

#include <iostream>

#include <stdlib.h>

 

using namespace std;

 

int main() {

        int ret;

        ret = system("Python ck.py ok go");

        cout << "ret/cpp = " << ret << endl;

        cout << "Enter any character -> ";

        char c;

        cin >> c;

        return 0;

}

 

The Python script called by the above C function system is this, whose name is ck.py, and is stored in the current folder at the time when the C program is running.

 

import sys

import subprocess

print(sys.argv)

ret = subprocess.call('dir', shell = True)

print('Goodbye !, ret = ', ret)

 

The above script calls command dir by subprocess.call.

 

Figure 1 shows the console window, displayed when the program is running.

Figure 1

 

Press any character key, and press Enter-key. Then the program will exit.

 

Up