Solved

How to convert Python code to C++ code

Posted on 2009-05-20
10
2,217 Views
Last Modified: 2012-05-07
Hello,

Can you please tell me how to convert Python code to C++ code.

Thanks
0
Comment
Question by:davinder101
  • 3
  • 3
  • 2
  • +2
10 Comments
 
LVL 41

Accepted Solution

by:
HonorGod earned 500 total points
ID: 24430691
Well, there is an experimental Python -> C++ compiler described here:

http://developers.slashdot.org/article.pl?sid=06/06/15/1623217

But your best bet would be to understand the Python application, and hand translate it.

This allows you to change the data structures being used to make use of ones that may make more sense in the target language.
0
 

Expert Comment

by:iamkorvus
ID: 24435343
The real question is why?  

If you are looking to make an executable file, you could try something like Py2Exe ( http://www.py2exe.org/ ), Py2App ( http://svn.pythonmac.org/py2app/py2app/trunk/doc/index.html ), cx_Freeze ( http://cx-freeze.sourceforge.net/ ), or bbfreeze ( http://pypi.python.org/pypi/bbfreeze/0.96.5 ).  

If you are looking to speed the code up, try psyco ( http://psyco.sourceforge.net/ ) first.  While there are applications for having C++ source, they are relatively few, so I want to make sure that you aren't assuming you need C++ source when you really just need a simple tool.
0
 
LVL 4

Expert Comment

by:manavsi
ID: 24439015
well try this:http://sourceforge.net/projects/py2cpp/

HTH
Manavsi
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 28

Expert Comment

by:pepr
ID: 24439062
Well, I understand the "why". I personally have found some nice functionality implemented via standard modules. Also, I have got used to to some way of thinking suggested by Python (via API). For example, the os.path or os module contains very usefull functions that are otherwise usually done not so nicely -- say, os.path.join().

This way I have implemented my own implementation of C++ code that follows the API -- not completely, only the functions that I really need. I do copy the module namespaces. Then instead of Python's os.path.join(a, b, c) I do write os::path::join(a, b, c);

Of course, it is probably not a good idea to bend the C++ to the form of Python completely. For example std::map<> is just fine. Also trying to implement containers that can contain any type may not be the most important thing.

To summarize: I feel that there may be two reasons for conversion of the Python code to the C++ code -- 1) to use the similar API in your C++ program (then implement the API also in C++ and translate by hand as HonorGod wrote), 2) to have the separate .exe for the installation or efficiency (speed) reason (then iamkorvus recommendations hold).
0
 

Author Comment

by:davinder101
ID: 24439364
Thanks for reply,

I am having one software along with its source code which is written in Python language and i don't know Python language as i am working in VC++ on Windows-XP. I want to convert this Python code to C++ code so that i can modify code futher as i needed.

From the link http://developers.slashdot.org/article.pl?sid=06/06/15/1623217 i downloaded the software but i am not able to convert Python code to C++ code, please tell me how to install it on Windows-XP and how to run it.

The other link http://sourceforge.net/projects/py2cpp/ does't have exe file to download.

I learn little bit Python lagauge and i am able to write small program and try to debug it, but the software which i want to convert in C++ is mainly written for linux system, its exe runs on XP but when i am going to debug it, It shows some files missing error.
Please help me out.
0
 
LVL 4

Expert Comment

by:manavsi
ID: 24447987
well davinder101,
try the following code in Perl, it takes in a python file and try to convert it to a cpp file... May be give it a try..
Well, it cant do all advanced convertions... but a pure python file would be good to go i suppose...

Please give it a try... Always backup your original code... :)

HTH
Manavsi
#!/usr/bin/perl
# Hideous evil script for converting python into C++
# 
# Takes in a python file, and produces a C++ header file + code file
# which contain the same code with an attempt made to make the syntax
# a bit more like C++. The header file contains the class definitions
# and the code file contains any functions.
#
# This is just a try, if you can, well and good... if not learn the 
# language and convert it yourself.. :)
# 
# Hope This Helps
# Manavsi
 
$qcomment = 0;
$insideclass = 0;
$insidefunc = 0;
@struct_indents = ();
$struct_indent = "";
%methods = ();
%members = ();
 
 
open(HEADER, ">file.h");
open(CODE, ">file.cpp");
 
print(CODE "#include \"file.h\"\n");
print(HEADER "typedef int bad_type; // Remove this to get unset type reporting\n\n");
 
MAIN: while (<>) {
	s/\t/        /g;
	/([\s]*)(.*)$/;
	$head = $1;
	$body = $2;
	### Eliminate commentaries
        if ($body =~ /"""/) {
		unless ($body =~ /""".*"""/) {
			if ($qcomment == 1) {
				$qcomment = 0;
			} else {
				$qcomment = 1;
			}
		}
		next MAIN;
	}
	### Skip if we are in commentary
        next MAIN if ($qcomment == 1);
	### If line is blank, store this fact
	if (length($body) == 0) {
		$crs = $crs."\n";
		next MAIN;
	}
	### Skip a comment line
	next MAIN if ($body =~ /^#/);
	$body =~ s/#/\; \/\//;
	### Work out if we have to print any }s as resuly of an
	### indentation change
	### First check for end of any control structures
	while (($#struct_indents != -1) && (length($head) <= length($struct_indent))) {
		print(CODE $struct_indent."}\n");
		$struct_indent = pop(@struct_indents);
	}
	### Now check for the end of a function
	if (($insidefunc) != 0) {
		if ((length($head) <= length($findent)) && (length($body) != 0)) {
			print(CODE $findent."}\n");
			$insidefunc = 0;
			@struct_indents = ();
			$struct_indent = "";
		}
	}
	### Now check for the end of a class
	if (($insideclass) != 0) {
		if ((length($head) == 0) && (length($body) != 0)) {
			@member_list = values(%members);
			%members = ();
			while ($#member_list != -1) {
				print(HEADER pop(@member_list));
			}
			print(HEADER "\n    public:\n");
			@method_list = values(%methods);
			%methods = ();
			while ($#method_list != -1) {
				print(HEADER pop(@method_list));
			}
			$insideclass = 0;
			print(HEADER "};\n\n");
		}
	}
	### Now we have processed any indentation change we can
	### print any newlines which we have stored up
	print(CODE $crs);
	$crs="";
	if (($insideclass || $insidefunc) == 0) {
		### Check for the beginning of class
		if ($body =~ /^class +([^:()]+)(\(([^():]+)\))?:/) {
			print(HEADER "class ".$1);
			if (length($3) != 0) {
				print(HEADER " : public ".$3);
			}
			print(HEADER " {\n");
			$insideclass = 1;
			$classname = $1;
			next MAIN;
		}
		### Check for an import line
		if ($body =~ /^(from\s*([^ ]*)\s*)?import (.*)$/) {
			#print(CODE "#include <".$2."/".$3.".h>\n");
			next MAIN;
		}
	}
	### Check for the beginning of function
	if ($insidefunc == 0) {
		if ($body =~ /def\s+([^ ()]+)\(\s*(self\s*,?\s*)?([^()]*)\):$/) {
		    $fname=$1;
		    $args=$3;
		    $args =~ s/([A-Za-z_\-]+)/bad_type $1/g;
		    if ($insideclass == 1) {
			if ($fname eq "__init__") {
				print(CODE $head.$classname."::".$classname."(".$args.") {\n");
				$methods{$classname}=$head.$classname."(".$args.");\n";
			} else {
				print(CODE $head."bad_type ".$classname."::".$fname."(".$args.") {\n");
				$methods{$fname}=$head."bad_type ".$fname."(".$args.");\n";
			}
		    } else {
			print(HEADER $head."bad_type ".$fname."(".$args.");\n");
			print(CODE $head."bad_type ".$fname."(".$args.") {\n");
		    }
		    $findent = $head;
		    $insidefunc = 1;
		    next MAIN;
		}
	}
	### Check for member function calls
	if (($insideclass && $insidefunc) != 0) {
		while ($body =~ s/self.([A-Za-z_\-\.]+)\(/$classname\:\:$1\(/) {}
		while ($body =~ s/self.([A-Za-z_\-]+)/$classname\:\:$1/) {
			$members{$1}="        bad_type ".$1.";\n";
		}
	}
	if (($insideclass || $insidefunc) == 0) {
		$body =~ s/^/\/\/ /;
	}
	### Check for any control structures
	if ($body =~ /^if\s+(.*):\s*(.*)$/) {
		##### IF
		print(CODE $head."if (".$1.") {\n");
		$body = $2;
		push(@struct_indents,$struct_indent);
		$struct_indent = $head;
		$head = $head."    ";
	} elsif ($body =~ /^elif\s+(.*):\s*(.*)$/) {
		##### ELIF
		print(CODE $head."else if (".$1.") {\n");
		$body = $2;
		push(@struct_indents,$struct_indent);
		$struct_indent = $head;
		$head = $head."    ";
	} elsif ($body =~ /^else:\s*(.*)$/) {
		##### ELSE
		print(CODE $head."else {\n");
		$body = $2;
		push(@struct_indents,$struct_indent);
		$struct_indent = $head;
		$head = $head."    ";
	} elsif ($body =~ /^for\s+(.+\s+in\s+.+):\s*(.*)$/) {
		##### FOR
		print(CODE $head."for (/*".$1."*/) {\n");
		$body = $2;
		push(@struct_indents,$struct_indent);
		$struct_indent = $head;
		$head = $head."    ";
	} elsif ($body =~ /^while\s+(.*):\s*(.*)$/) {
		##### WHILE
		print(CODE $head."while (".$1.") {\n");
		$body = $2;
		push(@struct_indents,$struct_indent);
		$struct_indent = $head;
		$head = $head."    ";
	} elsif ($body =~ /^try:\s*(.*)$/) {
		##### TRY
		print(CODE $head."try {\n");
		$body = $2;
		push(@struct_indents,$struct_indent);
		$struct_indent = $head;
		$head = $head."    ";
	} elsif ($body =~ /^except\s*\(?(.*)\)?\s*:\s*(.*)$/) {
		### EXCEPT
		print(CODE $head."catch (".$1.") {\n");
		$body = $2;
		push(@struct_indents,$struct_indent);
		$struct_indent = $head;
		$head = $head."    ";
	}
	### If we still have anything left in $body, print the line
	### If nothing has been changed yet, then this will always be true
	if (length($body) != 0) {
		print(CODE $head.$body.";\n");
	}
}
 
if ($insideclass != 0) {
	print(HEADER "};\n");
}
 
if ($insidefunc != 0) {
	print(CODE $findent."}\n");
}
 
close(CODE);
close(HEADER);

Open in new window

0
 

Author Comment

by:davinder101
ID: 24456999
how to write this code in perl i do't know about perl? as i am working on vc++.
0
 
LVL 41

Expert Comment

by:HonorGod
ID: 24458401
> How do I write [execute] this? ...

- Download Perl from activestate
  http://www.activestate.com/activeperl/
- Install it,
- open a command prompt
- cd to the directory containing the code to be converted
- execute it:

  perl file1.py file2.py file3.py
0
 

Author Comment

by:davinder101
ID: 24470612
the code which you provided perl to c++ does't not convert in c++, it on make .cpp and .h files and copy python code to it with comment sign.
0
 
LVL 41

Expert Comment

by:HonorGod
ID: 24933995
Thanks for the grade & points.

Good luck & have a great day.
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article will show the steps for installing Python on Ubuntu Operating System. I have created a virtual machine with Ubuntu Operating system 8.10 and this installing process also works with upgraded version of Ubuntu OS. For installing Py…
Flask is a microframework for Python based on Werkzeug and Jinja 2. This requires you to have a good understanding of Python 2.7. Lets install Flask! To install Flask you can use a python repository for libraries tool called pip. Download this f…
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question