I have one completed python program called email.py, this program was used to send a an email to a preset address. Is there a way that I can invoke this python file in c++ context? Like one c++ function that can invoke and run email.py?
Asked
Active
Viewed 90 times
-1
-
1Possible duplicate of [Calling Python script from C++ and using its output](https://stackoverflow.com/questions/16962430/calling-python-script-from-c-and-using-its-output) – Magix May 07 '18 at 02:45
-
2Perhaps stop in at the [help section (how to ask a question)](https://stackoverflow.com/help/how-to-ask) of stack overflow. It's a valuable resource for newer users like yourself. Also, you should try to search for the fix yourself next time. I did a short google and found thousands upon thousands of results to fix this exact issue. – James Whyte May 07 '18 at 02:48
1 Answers
3
Use system
in the stdlin.h
library. This does not capture the output or anything regarding the exit status of the program. It simply invokes it as if you typed it on the command line
#include <stdlib.h>
int main() {
// Command as a string
char* command = "python email.py";
// Call it
system(command);
return 0;
}
This is a very simply solution. There are libraries such as as Boost that allows you to import Python into C++.
-
hi, I tried your method, it said " module 'smtplib' has no attribute 'SMTP' "(mail = smtplib.SMTP is the code in my python file), so I think the location of my email.py file is wrong, where should I put my email.py file? – Jeff May 07 '18 at 02:57
-
1That's a problem with the Python code. Your code is probably importing the python module `smtplib`. It may be that your computer is running a newer or older version of python than that module requires, and something in the module has been moved. I've run across similar issues with the http libraries. But, I am not sure how to solve that. That has nothing to do with the C++ program running the Python program. Does the python program invoke successfully when run directly from command line? – May 07 '18 at 03:10