I'm new to C++ and I want to run this C++ code using python.
The C++ code
#include <stdio.h>
int main() {
printf("hello this is inside c++ ");
return 0;
}
The Python Code
import subprocess
print("in python file")
subprocess.call(["gcc", "c_file.cpp"])
subprocess.call("./a.out")
print("task is done")
The error I'm getting when I run using the python file
Traceback (most recent call last):
File "C:\Users\Amiru Randil\PycharmProjects\pythonRunC++Code\main.py", line 5, in <module>
subprocess.call(["gcc", "c_file.c"])
File "C:\Python382\lib\subprocess.py", line 349, in call
with Popen(*popenargs, **kwargs) as p:
File "C:\Python382\lib\subprocess.py", line 947, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "C:\Python382\lib\subprocess.py", line 1416, in _execute_child
hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified
Can you compile and run the cpp file standalone? That is, are you able to run it normally? Because I do not see any error in your code apart from thinking that you have not installed the c++ compiler.
Here is my c_file.cpp:
#include <stdio.h>
int main() {
printf("hello this is inside c++\n");
return 0;
}
and this is my run_c.py:
import subprocess
print("in python file")
subprocess.call(["g++", "c_file.cpp"])
subprocess.call("./a.out")
print("task is done")
When I run it, I get the correct output printed. Like so:python run_c.py
in python file
hello this is inside c++
task is done
As your error shows you are in windows so the executable will not be called a.out it will be a.exe also./ is not used in windows.
import subprocess
print("in python file")
subprocess.call(["gcc", "c_file.cpp"])
# change ./a.out to a.exe
subprocess.call("a.exe")
print("task is done")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.