Executing C++ code from python

隐身守侯 提交于 2021-02-07 08:59:43

问题


I am a beginner to python, and I have no idea if this seems to be a doable thing.

I have a simple loop in python that gives me all the files in the current directory. What I want to do is to execute a C++ code I wrote before on all those files in the directory from python

The proposed python loop should be something like this

import os
for filename in os.listdir(os.getcwd()):
    print filename
    (Execute the code.cpp on each file with each iteration)

Is there any chance to do this?


回答1:


Fairly easy to execute an external program from Python - regardless of the language:

import os
import subprocess

for filename in os.listdir(os.getcwd()):   
    print filename
    proc = subprocess.Popen(["./myprog", filename])
    proc.wait()

The list used for arguments is platform specific, but it should work OK. You should alter "./myprog" to your own program (it doesn't have to be in the current directory, it will use the PATH environment variable to find it).



来源:https://stackoverflow.com/questions/40135225/executing-c-code-from-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!