在尼姆中,我可以编写以下代码来导入外部模块:
import myFancyPantsModule
...
# And here I'd use the fancyPants proc只要我有这个模块,它就能正常工作,但是对于那些可能下载代码而没有安装模块的人来说,编译将失败,并带来一条用户不太友好的消息:
$ nim c fancyProgram.nim
fancyProgram.nim(1, 7) Error: cannot open 'myFancyPantsModule'是否有任何方法可以对import进行包装,以便捕获类似于异常的异常,并执行类似于when语句的代码的另一个分支?我希望找到一些importable-like宏,或者一些我可以使用的东西,比如:
when importable(myFancyPantsModule):
# And here I'd use the fancyPants proc
else:
quit("Oh, sorry, go to https://github.com/nim-lang/nimble and install " &
" the myFancyPantsModule using the nimble package manager")事实上,我想让一些模块是可选的,而不是简单的错误消息,这样编译仍会继续进行,可能会减少功能。这个是可能的吗?
解决方案编辑:基于这里的答案--我的版本--如何解决这个问题,首先您需要一个具有以下源代码的moduleChecker二进制文件:
import os, osproc
let tmpFile = getTempDir() / "dynamicModuleChecker.nim"
proc checkModule(module: string) =
except:
echo "Cannot write ", tmpFile, " to check the availability of modules"
quit(1)
writeFile(tmpFile, "import " & module & "\n")
finally: removeFile(tmpFile)
except:
echo("Cannot run \"nimrod check\" to check the availability of modules")
quit(1)
if execCmdEx("nim check " & tmpFile).exitCode != 0:
echo("Cannot import module " & module & ".")
quit(1)
else:
echo "OK"
if ParamCount() < 1:
quit("Pass as first parameter the module to check")
else:
checkModule(ParamStr(1))然后,如果这个命令可用,可以使用以下宏:
import macros
macro safeImport(module, message: string): stmt =
if "OK" == gorge("./moduleChecker " & module.strVal):
result = newNimNode(nnkStmtList).add(
newNimNode(nnkImportStmt).add(
newIdentNode(module.strVal)))
else:
error("\nModule " & module.strVal &
" not available.\n" & message.strVal)
safeImport("genieos",
"Please install \"http://gradha.github.io/genieos/\"")不幸的是,必须生成一个单独的进程,不仅是为了外部编译,还需要另一个进程来生成要检查的临时文件,因为当前版本中没有在编译时生成文件的staticWrite。
发布于 2013-11-13 17:58:40
据我所知,没有(容易的)办法可以做到这一点。您可以做的是在构建中使用单独的配置/检查阶段。例如:
import macros, os, osproc
proc checkModule(module, howtomessage: string) =
except:
echo("Cannot write .conftest.nim to check the availability of modules")
quit(1)
writeFile(".conftest.nim", "import " & module & "\n")
except: nil
removeFile(".conftest.nim")
except:
echo("Cannot run \"nimrod check\" to check the availability of modules")
quit(1)
if execCmdEx("nimrod check .conftest.nim").exitCode != 0:
echo("Cannot import module " & module & ".")
echo(howtomessage)
quit(1)
checkModule "foobar", "Please install it using the Babel package manager"然后运行如下所示:
nimrod cc --run configure.nim && nimrod cc main.nim这是假设上面的代码存储在一个名为configure.nim的文件中,并且nimrod可执行文件在您的路径中(否则,您还必须在configure.nim中指定nimrod路径)。
https://stackoverflow.com/questions/19954952
复制相似问题