我想將文件數量轉換爲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