命令行工具脚本
脚本可用于创建利用 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; }
// create new document (off screen): var doc = new RDocument(new RMemoryStorage(), new RSpatialIndexNavel()); var di = new RDocumentInterface(doc);
// import given file: if (di.importFile(inFile) != RDocumentInterface.IoErrorNoError) { di.destroy(); print("Cannot import file:", inFile); return; }
// add line to drawing (using QCAD Simple API): startTransaction(di); addLine(0, 0, 100, 100); endTransaction();
// export to given file (-o) if (!di.exportFile(outFile)) { di.destroy(); print("Cannot export file:", outFile); return; }
di.destroy();}
if (typeof(including) == 'undefined' || including === false) { main();}运行命令行工具脚本
Section titled “运行命令行工具脚本”假设此脚本保存在 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