让C程序像python一样飞一会~

最近各种申实习太弱了申不上,决定多去练练C和算法。
问题出现,作为Pythoner最看不惯了就是写个C还要gcc -o…balabala编译一下,生成个.out,最后还要执行,最后有洁癖的我还得想办法清理掉那些.out们,伟大的

python x.py

是多么方便啊。
今天我完成了一项很爽的工作,拿走我的fuckc.py文件,放到/usr/local/bin/下,执行chmod a+x fuckc.py添加执行权限,刷各种oj算法题 or 面试真题的时候,只需要执行

fuckc.py x.c

就可以自动完成编译+执行+清理的工作,So easy!(用windows?加个Path吧; 用IDE不需要?额,每次打开IDE我的机子慢得像shi一样;)
当然,如果你觉得我的文件名字起得太没格调,你可以随意换一个甚至去掉.py的后缀,比如greatc…

fuckc.py:

#!/usr/bin/env python
#coding: utf-8

"""
$ fuckc.py xxx.c argv1 argv2 ...
equal to
$ g++ xxx.c -o xxx.out
$ ./xxx.out argv1, argv2...
$ rm xxx.out
"""
import sys
import os
import commands

# This is a decorator
def command_info_printer(func):
	def wrapper(*args):
		return_val_tuple = func(*args)
		assert len(return_val_tuple) > 1
		status, output = return_val_tuple[0], return_val_tuple[1]
		if status != 0:
			print '[Error]', output
			return
		if output:
			print output
		return return_val_tuple
	return wrapper

def c_file_exists(c_file_path):
	return os.path.isfile(c_file_path)

def get_file_totalpath(filename):
	return os.path.join(os.getcwd(), filename)

@command_info_printer
def exec_c_compile(c_file_path, c_out_filename = None):
	"""
	a.c/a.cpp/a.C/a.cxx...   --->   a.out
	a                        --->   a.out
	This function also accept an out_filename argument.
	"""
	ex_index = c_file_path.find('.')
	if not c_out_filename:
		c_out_file = c_file_path if ex_index == -1 else c_file_path[:ex_index]
	else:
		c_out_file = c_out_filename
	c_out_file += '.out' # give a .out extension

	shell_command = 'g++ -o ' + c_out_file + ' ' + c_file_path
	status, output = commands.getstatusoutput(shell_command)
	return status, output, c_out_file

@command_info_printer
def exec_c_program(c_out_file, c_argv_list):
	shell_command = get_file_totalpath(c_out_file) + ' ' + ' '.join(c_argv_list)
	status, output = commands.getstatusoutput(shell_command)
	return status, output

@command_info_printer
def do_clean(c_out_file):
	shell_command = 'rm ' + get_file_totalpath(c_out_file)
	status, output = commands.getstatusoutput(shell_command)
	return status, output
	
def main():
	argv_list = sys.argv
	if len(argv_list) < 2:
		print '[Error]Need c/c++ file as argument'
		return
	c_file_path, c_argv_list = argv_list[1], argv_list[2:] # c_argv_list will be passed to executive program
	if not c_file_exists(c_file_path):
		print '[Error]c/c++ file %s not exists' % c_file_path
		return
	status, output, c_out_file = exec_c_compile(get_file_totalpath(c_file_path))
	exec_c_program(c_out_file, c_argv_list)
	do_clean(c_out_file)

if __name__ == '__main__':
	main()

「注」如果有bug,可以自行修改代码。当然更欢迎report在下面告知我~同时你也可以自行添加新的特性~

7 thoughts on “让C程序像python一样飞一会~”

发表评论

电子邮件地址不会被公开。 必填项已用*标注

Click the right image To submit your comment: