我想将文件数量转换为C中的静态字符串声明。我试图用Python编写一个快速脚本(如下所示),但它看起来并不简单,问题出现了,试图编译输出。将文件转换为静态C字符串声明
import os, sys
from glob import glob
from re import sub
test_dirs = ('basics', 'float', 'import', 'io', 'misc')
tests = sorted(test_file for test_files in (glob('{}/*.py'.format(dir)) for dir in test_dirs) for test_file in test_files)
def cfunc_name(t):
return sub(r'/|\.|-', '_', t)
for t in tests:
print("void {}(void* data) {{".format(cfunc_name(t)))
with open(t) as f:
lines = ''.join(f.readlines())
cstr = sub('"', '\\"', lines)
cstr = sub('\n', '\"\n\"', cstr)
print(" const char * pystr = \"\"\n\"{}\";".format(cstr))
print("end:\n ;\n}")
print("struct testcase_t core_tests[] = {")
for t in tests:
print(" {{ \"{}\", test_{}_fn, TT_ENABLED_, 0, 0 }},".format(t, cfunc_name(t)))
print("END_OF_TESTCASES };")
寻找现有的工具是不完全明显(可能是我的搜索关键词是不完全正确)...有一个简单的UNIX工具,做这样或有没有人遇到类似的东西来吗?
非打印/控制字符(你所提到的新行)和正确的字符编码也很重要。 – Deduplicator
我设法绕过换行符和内部双引号,但是像_“十六进制转义序列超出范围”这样的编译器错误_有点极端,我真的不想处理(除非必须)。 – errordeveloper
我真的认为你会更好地使用链接的项目(这不是我的项目)。你发布的代码真的很离谱。 'sub('\ n','\'\ n \'',cstr)'应该是'sub(“\ n”,'\\ n',cstr)''''''如果我正在写东西,我会替换这些:http://en.cppreference.com/w/cpp/language/escape加上不在32-127之间的任何字符。请注意,\ xHH语法只能编码一个*字节*,即0-255--所以要小心python的Unicode处理,除非您使用\ u或\ U而不是 – teambob