Python program Executing C++ Program Containing
Arrays
In our previous program to check whether a
number is a palindrome number or not you have used only control structure
statements. Now you are going to execute a C++ program containing array.
Write a C++ program to print Transpose of a matrix(2
D array).*/
//Now select File->New in Notepad and type the C++ program
#include <iostream>
using namespace std;
int main()
{
int a[3][3], i, j;
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{ cout<<"enter the value for
array["<<i+1<<"]"<<"["<<j+1<<"]
:"; cin>>a[i][j];
}
}
system("cls");
cout<<"\n\nOriginal Array\n";
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
cout<<a[i][j]<<' ';
cout<<endl;
}
cout<<"\n\n The Transpose of
Matrix\n";
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
cout<<a[j][i]<<' ';
cout<<endl ;
}
return 0;
}
// Save this file as trans_cpp.cpp
//Now select File→New in Notepad and type the Python program
#Save the File as
transpose.py.Program that compiles and executes a .cpp file
#Python tanspose.py -i trans_cpp
import sys, os, getopt
def main(argv):
cpp_file = ''
exe_file = ''
opts, args = getopt.getopt(argv, "i:",['ifile='])
for o, a in opts:
if o in ("-i", "--ifile"):
cpp_file = a + '.cpp'
exe_file = a + '.exe'
run(cpp_file, exe_file)
def run(cpp_file, exe_file):
print("Compiling " + cpp_file)
os.system('g++ ' + cpp_file + ' -o ' +
exe_file)
print("Running " + exe_file)
print("-------------------")
print
os.system(exe_file)
print
if __name__ =='__main__':
main(sys.argv[1:])
Output of the above program
Original Array
1 2 3
4 5 6
7 8 9
The Transpose of Matrix
1 4 7
2 5 8
3 6 9
You would have noticed the Python program used
to execute the transpose of a matrix is also the same as what you have used in
palindrome program. From this what you have understood?
The Python script (program) in this chapter is
mainly used to read the C++ file along with the type of mode used like ‘i’/’o’.
It Parses (splits) each value of the command line and pass as argument to the
List called “opts”. The entire C++ code is referenced for reading by “long
option ifile” along with the mode.
The List ‘o’ in “for loop” contains the mode
(‘i’) and the variable ‘a’ contains the C++ file with its complete path
(Example [<‘c:\pyprg\cpp_file’>,’ trans_cpp’ ]) The extensions like cpp/
exe are added by the Python script.
__name__ variable directs the program to start
from the Python script’s “main” definition. The “main” definition does the
Parsing and adding the extensions. The “run” definition invoke the “g++”
compiler and creates the exe file. The system() command of “os” module executes
the exe file and you will get the desired output. The file extensions are added
by the Python script due to which you can even execute the C programs.
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.