kar*_*r41 8 windows bash compilation python-3.x
我一直在编写一个简单的 python 脚本来编译和运行给定的 .cpp 文件。
我已经让它按预期工作,但我希望能够在 .cpp 文件的编译产生错误或警告时停止脚本,而不是继续执行 .exe 文件。
# run_cpp.py
# Script that compiles and executes a .cpp file
# Usage:
# python run_cpp.py -i <filename> (without .cpp extension)
import sys, os, getopt
def main(argv):
cpp_file = ''
exe_file = ''
try:
opts, args = getopt.getopt(argv, "hi:",["help",'ifile='])
except getopt.GetoptError as err:
# print help information and exit
print(err)
usage()
sys.exit(2)
for o, a in opts:
if o in ("-h", "--help"):
usage()
sys.exit()
elif o in ("-i", "--ifile"):
cpp_file = a + '.cpp'
exe_file = a + '.exe'
run(cpp_file, exe_file)
def usage():
print('run_cpp.py -i <filename> (without .cpp extension)')
def run(cpp_file, exe_file):
os.system("echo Compiling " + cpp_file)
os.system('g++ ' + cpp_file + ' -o ' + exe_file)
os.system("echo Running " + exe_file)
os.system("echo -------------------")
os.system(exe_file)
if __name__=='__main__':
main(sys.argv[1:])
Run Code Online (Sandbox Code Playgroud)
当我在 Windows MINGW 上运行以下命令时,一切都很好。
$ python run_cpp.py -i hello
Compiling hello.cpp
Running hello.exe
-------------------
Hello, world!
Run Code Online (Sandbox Code Playgroud)
其中 hello.cpp 是:-
#include <iostream>
using namespace std;
int main() {
cout << "Hello, world!" << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果我在 endl 之后省略分号,则尽管存在编译错误,脚本仍会继续运行 .exe 文件。
$ python run_cpp.py -i hello
Compiling hello.cpp
hello.cpp: In function 'int main()':
hello.cpp:8:5: error: expected ';' before 'return'
return 0;
^~~~~~
Running hello.exe
-------------------
Hello, world!
Run Code Online (Sandbox Code Playgroud)
在尝试运行 .exe 文件之前,如何让我的脚本知道编译是否成功?
我已经根据答案更新了代码。
if os.system('g++ ' + cpp_file + ' -o ' + exe_file) == 0:
os.system(exe_file)
Run Code Online (Sandbox Code Playgroud)
现在脚本只会在编译成功时执行.exe 文件。
另一种方法可以做同样的事情,但使用subprocess库而不是os库,正如 python 文档所推荐的那样 -
def run(cpp_file, exe_file):
x = subprocess.getoutput('g++ ' + cpp_file + ' -o ' + exe_file)
if x == "": # no error/warning messages
subprocess.run(exe_file) # run the program
else:
print(x) # display the error/warning
Run Code Online (Sandbox Code Playgroud)
所有命令都会返回一个退出代码,指定命令是否成功,对于某些命令特定的成功定义。os.system通常返回此退出代码,0通常表示“成功”,任何其他退出代码表示错误:
if os.system("g++ foo.c") == 0:
print ("Worked")
else:
print ("Failed")
Run Code Online (Sandbox Code Playgroud)
该文档提到了一些注意事项和更好的 API 使用:
在 Unix 上,返回值是以 wait() 指定的格式编码的进程的退出状态。请注意,POSIX 没有指定 C system() 函数的返回值的含义,因此 Python 函数的返回值是与系统相关的。
在Windows上,返回值是运行命令后系统shell返回的值。shell由Windows环境变量COMSPEC给定:通常是cmd.exe,它返回命令运行的退出状态;在使用非本机 shell 的系统上,请查阅您的 shell 文档。
subprocess 模块提供了更强大的工具来生成新进程并检索其结果;使用该模块比使用此功能更好。请参阅子流程文档中的用子流程模块替换旧函数部分,以获取一些有用的秘诀。
| 归档时间: |
|
| 查看次数: |
14441 次 |
| 最近记录: |