• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2384
  • Last Modified:

How to convert Python code to C++ code

Hello,

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

Thanks
0
davinder101
Asked:
davinder101
  • 3
  • 3
  • 2
  • +2
1 Solution
 
HonorGodCommented:
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
 
iamkorvusCommented:
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
 
manavsiCommented:
well try this:http://sourceforge.net/projects/py2cpp/

HTH
Manavsi
0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

 
peprCommented:
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
 
davinder101Author Commented:
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
 
manavsiCommented:
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
 
davinder101Author Commented:
how to write this code in perl i do't know about perl? as i am working on vc++.
0
 
HonorGodCommented:
> 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
 
davinder101Author Commented:
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
 
HonorGodCommented:
Thanks for the grade & points.

Good luck & have a great day.
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 3
  • 3
  • 2
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now