Link to home
Start Free TrialLog in
Avatar of Praveen K
Praveen K

asked on

App or script that can translate python file to cpp

I have some Python code I need to translate into C++. I don't have a lot of experience with C++. Does anyone have suggestions on the best way to go about this?

Is there an app or anything I can use to do this process quickly?

Thanks
maxtemp_map.py
maxtemp_reduce.py
Avatar of noci
noci

Cython?  
See here: https://cython.org 
or here: https://pypi.org/project/Cython/

the call would be: cython --cplus your.py program....

( btw: the code will look ugly & big  as most generated code does ]
Avatar of Praveen K

ASKER

Could you please Translate if possible
See attached files.
cython --cplus maxtemp_map.py
cython --cplus maxtemp_reduce.py.

(you may still need Python include files though).
maxtemp_map.cpp
maxtemp_reduce.cpp
Sorry For your inconvenience, Can you translate manually?  if possible because of cython cpp code is not executed properly.
Thanking you,
Why do you want to translate your code into C++?
For performance?
For embedding it in another executable?
For allowing to run it without having to install python on a target machine?

I am asking for the exact reason as this might impact the response.

Do you just want to have a standalone executable?
You might just use pyinstaller.  ( https://www.pyinstaller.org/ )
Here the code is not translated into CPP, but you can run your code without installing python on a given platform

Then you have nuitka, that tries to compile python code into C-code ( https://nuitka.net/pages/overview.html )
which runs then again as a stand alone executable.

for this install nuitka with
pip install nuitka

Open in new window


then run
python -m nuitka --follow-imports maxtemp_map.py

Open in new window


You should now have an executable called maxtemp_map.bin  (approximate file size 2MB) which you can call.
and the whole C (but not CPP) code can be found in maxtemp_map.build.

Again whether any of these answers is useful really depends on your exact reason why you want to convert python to cpp.
I have some Assignment So I'm trying to translate python code to cpp but I don't have experience on cpp
If it is an assignment, then I think you are looking for a manual translation.
All above tools will spit out code, that is far too complicated.

For maxtemp_map.py for example this could mean to perform following manual steps:

The py code is rather short:
import re
import sys

for line in sys.stdin:
    val = line.strip()
    year, temp, q = val[15:19], val[87:92], val[92:93]
    if (temp != "+9999" and re.match("[01459]", q)):
        print("%s\t%s" % (year, temp))

Open in new window



-  write a hello_world program
- remove the hello world print and modify it to read lines and print them
- write a CPP function, that performs the strip function. (strip of all leading and treailing white space)
 and insert in in your code and print now the stripped line instead of the original line
- write a function, that splits the stripped line into year, temp and q
  and insert it in the code and print now year, temp, q
- insert the if statement and print only the lines for which the condition is true.
look at this code:

#include <string>
#include <iostream>

int main()
{
    std::string line, val, year, temp;
    int ret = -1;
    char q = '\0';
    while (std::getline(line, cin))
    {
       int beg = (int)line.find_first_not_of(" \n\r\t");
       int end = (int)line.find_last_not_of(" \n\r\t"); 
       int len = end - beg;
       if (len < 93)
          continue;  // string is too short
       val  = line.substr(beg, len);
       year = val.substr(15, 4);
       temp = val.substr(87, 5);
       q    = val[92];
       if (temp != "+9999" && 
           std::string("01459").find(q)>= 0)
       {
           std::cout << year << '\t' << temp << '\n';
           ret = 0;
       }
    }
    return ret;
}

Open in new window


the code is not tested but should compile beside of typing errors.

you may try to write the code for the second function yourself. the split function could be made by searching for '\t' in the string and then use substr function. the conversion from string to int by using istringstream:

#include <sstream>

...

std::istringstream iss(val);
int ival;
if (iss >> ival)
{
     // val successfully was converted to int

Open in new window

 
Sara
Didn't write C for many years and C++ for over 10 years and I never really wrote C++, so this might might not be the best solution, but it might give you one example of how to get started.

1.) Google for "C++ hello world"
#include <iostream>
using namespace std;

int main()
{
    cout << "Hello, World!\n";
    return 0;
}

Open in new window


2.) change  code main() to read a  line and writes it out (Google for C++ read line from stdin)
int main()
{
    string str;
    getline(cin, str);
    cout << str << "\n";
    return 0;
}

Open in new window


2.) Change code to read multiple lines:
I also added leading and trailing ## to the output, so that it's easier to see the leading and trailing white spaces.
And I also display the length of the string (all this just for debugging)
int main()
{
    string str;
    while(getline(cin, str)){
        cout << "##" << str << "##" << str.length() << "\n";
    }
    return 0;
}

Open in new window


Next step is to write code, that removes the leading white space and extracts sub strings.

You can look for the methods string::find_first_not_of() and string::substr()
Ah just saw, that sarabande wrote already an answer.

I wouldn't perform the complete strip as it is in fact of no use (in this context)
The python script would have worked the same way with an lstrip() (just stripping off the left white spaces)
My complete solution with only left strip and only string types.
The best solution would probably to take sarabande's code and get rid of the right strip.

[#include <iostream>
using namespace std;



int main()
{
    string str;
    string whitespace = " \t";  // string containing all white space characters to strip
    string valid_q_values = "01459";

    string left_stripped;
    string year, temp, q;

    while(getline(cin, str)){
        // determine position of first white space character
        int first_pos = str.find_first_not_of(whitespace);
        // cout << "##" << str << "##" << str.length() << "/" << first_pos << "\n";
        left_stripped = str.substr(first_pos);
        // cout << "##" << left_stripped << "##\n";

        // not really necessary, but makes code more robust against invalid lines
        if (left_stripped.length() < 93){
            cout << "ignoring line that is too short\n";
            continue;
        }
        year = left_stripped.substr(15,4);
        temp = left_stripped.substr(87,5);
        q = left_stripped.substr(92, 1);
        // cout << "##" << left_stripped << "##\n";
       // cout << year << "\t" << temp << q << "\n";
        if (temp != "+9999" && q.find_first_not_of(valid_q_values)){
            cout << year << "\t" << temp << "\n";
        }

    }
    return 0;
}

Open in new window


Now you still have to translate max_temp_reduce.
Author said:
thank you for your help

Makes me think that there may be a solution in this question.
python is installed on most linux systems nowadays as many many tools are written in it. Almost like perl years ago.

Question was about an automated way to translate Python to C++, Cython does just that, so i have the opinion the answer has been given.
The code is Ugly, still needs some python libraries around. etc.
Perhaps the author clicked accidentally on the delete the request.

The explanation of the close request (  thank you for your help ) might be an indication.

I think the answers were given and even more help was provided.

After asking for clarifications we learned that:
I have some Assignment So I'm trying to translate python code to cpp but I don't have experience on cpp

Such a tool, that translates python code to C++ code, that could be accepted as solution for an assignment does very probably not exist.

There are however automated solutions to translate to unreadable / executable code.

E.g. nuitka for translating to C or Cython

For one of the the two python scripts two manual translations were given.

And hints were given of how to write the translation for the second script.

If the author found any better solution it might be interesting to mention it in the closing request.
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.