我試圖編寫一個Python腳本,它通過subprocess.Popen()調用g ++。exe文件並使用它將.cpp文件編譯爲一個.exe文件。問題是,不管我怎麼努力的路徑傳遞到源文件,我得到以下錯誤:在Windows上使用g ++從Python腳本編譯C++代碼
g++.exe: error: CreateProcess: No such file or directory
我的目錄結構如下:
D:/Test/test.py
D:/Test/external/mingw64/g++.exe
D:/Test/c/client/client.cpp
而且我的代碼是:
import os, subprocess
class builder():
def __init__(self):
self.gccPath = os.path.abspath("external/mingw64/g++.exe")
self.sourceDir = os.path.abspath("c/client")
self.fileName = "client.cpp"
self.sourceFile = os.path.join(self.sourceDir, self.fileName)
def run(self):
command = [self.gccPath, self.sourceFile , "-o", "client.exe"]
print command
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
n=1
while True:
nextLine = process.stdout.readline()
if nextLine == '' and process.poll() != None:
break
if nextLine != "" and nextLine != None:
print n, nextLine
n=n+1
builder = builder()
builder.run()
只是一些我試圖通過該路徑的方式:
Command: ["D:\\Test\\external\\mingw64\\g++.exe", "c/client/client.cpp", "-o", "client.exe"]
Command: ["D:\\Test\\external\\mingw64\\g++.exe", "c\\client\\client.cpp", "-o", "client.exe"]
Command: ["D:\\Test\\external\\mingw64\\g++.exe", "D:\\Test\\c\\client\\client.cpp", "-o", "client.exe"]
我也試過路過CWD到POPEN:
command = [self.gccPath, "client.cpp", "-o", "client.exe"]
process = subprocess.Popen(command, shell=True, cwd=self.sourceDir, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
總是同樣的錯誤。我之前使用過Popen很多次,這通常都是一件小事,所以我現在很害怕我做錯了什麼。
@ PM2Ring - 但我沒有加入兩條絕對路徑,我加入了一個字符串的絕對路徑。 我並不太在意路徑外觀,它們只是爲了調試目的而被打印出來。如果當我得到這個工作,所有打印將被刪除。 – Natsukane
聽起來像你正在嘗試構建一個構建系統。爲什麼不使用現有的像SCons(http://scons.org/)或CMake(https://cmake.org/)? –