Skip to content

命令列工具指令碼

指令碼可用於建立運用 QCAD 功能的命令列工具。例如,這樣的指令碼可以根據參數產生圖面、轉換圖面或分析圖面。

命令列工具指令碼的基本結構可以如下所示。這也是一個功能完整的範例指令碼,可作為命令列工具,用於在指定圖面中新增一條從 0,0 到 100,100 的線,並以新的檔案名稱匯出該圖面:

include("scripts/simple.js");
include("scripts/Tools/arguments.js");
function printHelp() {
print("Usage: " + args[1] + " [OPTION]... <drawing file>");
print();
print("This tool does...");
print();
print(" -f, -force Overwrite existing output file");
print(" -h, -help Display this help");
print(" -o, -outfile=FILE Set output file to FILE");
print(" -p, -parameter Some parameter...");
print(" ...");
printGenericUsage();
print();
}
function main() {
if (testArgument(args, "-h", "-help")) {
printHelp();
return;
}
if (args.length < 3) {
print("No input file given. Try -h for help.");
return;
}
var inFile = args[args.length - 1];
if (inFile.indexOf("-") === 0) {
print("No input file. Try -h for help.");
return;
}
var fi = new QFileInfo(inFile);
if (!fi.isAbsolute()) {
inFile = RSettings.getLaunchPath() + QDir.separator + inFile;
fi = new QFileInfo(inFile);
}
var outFile = getArgument(args, "-o", "-outfile");
if (outFile !== undefined) {
outFile = getAbsolutePathForArg(outFile);
}
else {
print("No output file. Try -h for help.");
}
if (new QFileInfo(outFile).exists() && !testArgument(args, "-f", "-force")) {
print("Output file exists already, not overwriting: ", outFile);
print("Use -f to force overwrite");
return;
}
// 建立新文件(螢幕外):
var doc = new RDocument(new RMemoryStorage(), new RSpatialIndexNavel());
var di = new RDocumentInterface(doc);
// 匯入指定的檔案:
if (di.importFile(inFile) != RDocumentInterface.IoErrorNoError) {
di.destroy();
print("Cannot import file:", inFile);
return;
}
// 將線新增至圖面(使用 QCAD Simple API):
startTransaction(di);
addLine(0, 0, 100, 100);
endTransaction();
// 匯出至指定的檔案 (-o)
if (!di.exportFile(outFile)) {
di.destroy();
print("Cannot export file:", outFile);
return;
}
di.destroy();
}
if (typeof(including) == 'undefined' || including === false) {
main();
}

假設此指令碼儲存於 scripts/Tools/ExTool/ExTool.js。

接著即可依下列方式執行:

qcad -autostart scripts/Tools/ExTool/ExTool.js -f -o out.dxf in.dxf

如果指令碼作為 Web 服務的一部分執行,請務必同時傳遞 -no-gui 與 -allow-multiple-instances 參數,以告知 QCAD 沒有可用的 GUI,且可以並行執行多個執行個體:

qcad -no-gui -allow-multiple-instances -autostart scripts/Tools/ExTool/ExTool.js -f -o out.dxf in.dxf

在伺服器上,您通常還會傳遞 -platform offscreen 以無介面方式執行(即在 Linux 上不需要 X11 伺服器):

qcad -platform offscreen -no-gui -allow-multiple-instances -autostart scripts/Tools/ExTool/ExTool.js -f -o out.dxf in.dxf