Home | | Computer Science 12th Std | Python Program to import C++

Chapter: 12th Computer Science : Chapter 14 : Integrating Python with MySql and C++ : Importing C++ Programs In Python

Python Program to import C++

Python contains many modules. For a problem Python allow programmers to have the flexibility in using different module as per their convenience.

Python Program to import C++

Python contains many modules. For a problem Python allow programmers to have the flexibility in using different module as per their convenience. The Python program what we have written contains a few new commands which we have not come across in basic Python program. Since our program is an integration of two different languages, we have to import the modules like os, sys and getopt.



Modular programming is a software design technique to split your code into separate parts. These parts are called modules. The focus for this separation should have modules with no or just few dependencies upon other modules. In other words: Minimization of dependencies is the goal.

But how do we create modules in Python? Modules refer to a file containing Python statements and definitions. A file containing Python code, for e.g. factorial.py, is called a module and its module name would be factorial. We use modules to break down large programs into small manageable and organized files. Furthermore, modules provide reusability of code. We can define our most used functions in a module and import it, instead of copying their definitions into different programs.


def fact(n):


if n == 0:

return 0

elif n == 1:

return 1


for i in range(1, n+1):

f= f*i

print (f)


>>>fact (5)


The above example is named as factorial.py


How to import modules in Python?

We can import the definitions inside a module to another module. We use the import keyword to do this. To import our previously defined module factorial we type the following in the Python prompt.

>>> import factorial

Using the module name we can access the functions defined inside the module. The dot (.) operator is used to access the functions. The syntax for accessing the functions from the module is

<module name> . <function name>

For example:



Python has number of standard (built in) modules. Standard modules can be imported the same way as we import our user-defined modules. We are now going to see the Standard modules which are required for our program to run C++ code.

(i) Python’s sys module

This module provides access to some variables used by the interpreter and to functions that interact strongly with the interpreter.


sys.argv is the list of command-line arguments passed to the Python program. argv contains all the items that come along via the command-line input, it's basically an array holding the command-line arguments of the program.

To use sys.argv, you will first have to import sys. The first argument, sys.argv[0], is always the name of the program as it was invoked, and sys.argv[1] is the first argument you pass to the program (here it is the C++ file). For example

main(sys.argv[1]): Accepts the program file (Python program) and the input file (C++  file) as a list(array). argv[0] contains the Python program which is need not to be passed because by default __main__ contains source code reference and argv[1] contains the name of the C++ file which is to be processed.

(ii) Python's OS Module

The OS module in Python provides a way of using operating system dependent functionality.

The functions that the OS module allows you to interface with the Windows operating system where Python is running on.

os.system(): Execute the C++ compiling command (a string contains Unix, C command which also supports C++ command) in the shell (Here it is Command Window). For Example to compile C++ program g++ compiler should be invoked. To do so the following command is used.

os.system (‘g++’ + <varaiable_name1> ‘-<mode>’ + <variable_name2>


os.system :- function system() defined in os module

g++ :- General compiler to compile C++ program under Windows Operating system.

variable_name1:- Name of the C++ file without extension .cpp in string format

mode :- To specify input or output mode. Here it is o prefixed with hyphen.

variable_name2 :- Name of the executable file without extension .exe in string format

For example the command to compile and execute C++ program is given below

os.system('g++ ' + cpp_file + ' -o ' + exe_file) : g++ compiler compiles the file cpp_file and –o (output) send to exe_file

(iii) Python getopt module

The getopt module of Python helps you to parse (split) command-line options and arguments. This module provides two functions to enable command-line argument parsing.

getopt.getopt method

This method parses command-line options and parameter list. Following is the syntax for this method –

<opts>,<args>=getopt.getopt(argv, options, [long_options])

Here is the detail of the parameters –

argv −        This is the argument list of values to be parsed (splited). In our program the complete command will be passed as a list.

options − This is string of option letters that the Python program recognize as, for input or for output, with options (like ‘i’ or ‘o’) that followed by a colon (:). Here colon is used to denote the mode.

long_options −This parameter is passed with a list of strings. Argument of Long options should be followed by an equal sign ('='). In our program the C++ file name will be passed as string and ‘i’ also will be passed along with to indicate it as the input file.

getopt() method returns value consisting of two elements. Each of these values are stored separately in two different list (arrays) opts and args .Opts contains list of splitted strings like mode, path and args contains any string if at all not splitted because of wrong path or mode. args will be an empty array if there is no error in splitting strings by getopt().

For example The Python code which is going to execute the C++ file p4 in command line will have the getopt() method like the following one.

opts, args = getopt.getopt (argv, "i:",['ifile='])

where opts contains : [('-i', 'c:\\pyprg\\p4')]

-i :- : option nothing but mode should be followed by :

'c:\\pyprg\\p4' : value nothing but the absolute path of C++ file.

In our examples since the entire command line commands are parsed and no leftover argument, the second argument args will be empty []. If args is displayed using print() command it displays the output as [].


Some more command for wrapping C++ code

if __name__=='__main__':


__name__ (A Special variable) in Python

Since there is no main() function in Python, when the command to run a Python program is given to the interpreter, the code that is at level 0 indentation is to be executed. However, before doing that, interpreter will define a few special variables. __name__ is one such special variable which by default stores the name of the file. If the source file is executed as the main program, the interpreter sets the __name__ variable to have a value as “__main__”.

__name__ is a built-in variable which evaluates to the name of the current module.

Thus it can be used to check whether the current script is being run on its own.

For example consider the following

if __name__ == '__main__':

main (sys.argv[1:])

if the command line Python program itself is going to execute first, then __main__ contains the name of that Python program and the Python special variable __name__ also contain the Python program name. If the condition is true it calls the main which is passed with C++ file as argument.

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
12th Computer Science : Chapter 14 : Integrating Python with MySql and C++ : Importing C++ Programs In Python : Python Program to import C++ |

Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.