我想在Windows下使用javascript(特别是nashorn)进行命令行脚本编写。通过命令行脚本,我的意思是使用JavaScript而不是.bat文件来执行各种命令行工具并处理它们的输出。一个正式的例子是here at oracle。在windows上使用JavaScript(nashorn)命令行脚本
在那里,他们展示了如何可以从.js
文件内$EXEC("ls -l")
执行shell命令和输出可以在$OUT
和$ERR
进行访问,如果你有
jjs script.js -scripting -- params
运行它。我做了大量的谷歌搜索,并没有提及任何地方(甲骨文和第三方博客文章,SO等),这是不支持在Windows上,但不知何故,所有的例子是与bash
命令。 这甚至可能在Windows上?
所以我可以在.js
脚本中编写例如。 $EXEC("dir")
并处理来自$OUT
的输出?
我有多远了:
如果脚本打
$EXEC
命令时,我不使用-scripting
参数有关jjs
,我只是得到ReferenceError: "$EXEC" is not defined
所以这可能不是要走的路。如果我确实使用
-scripting
param,$EXEC("cd c:")
会抛出下面的异常。这表明我可能会以错误的方式调用命令,或者路径或其他东西没有正确设置。
我在这里错过了什么?任何想法是赞赏。
环境的详细信息:
赢8.1
的Java 8,路径
jjs
(BIN)在系统的环境变量设置正确。
例外:
Exception in thread "main" java.lang.RuntimeException: java.io.IOException: Cannot run program "cd": CreateProcess error=2, The system cannot find the file specified
at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:382)
at jdk.nashorn.tools.Shell.apply(Shell.java:383)
at jdk.nashorn.tools.Shell.runScripts(Shell.java:312)
at jdk.nashorn.tools.Shell.run(Shell.java:168)
at jdk.nashorn.tools.Shell.main(Shell.java:132)
at jdk.nashorn.tools.Shell.main(Shell.java:111)
Caused by: java.io.IOException: Cannot run program "cd": CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
at jdk.nashorn.internal.runtime.ScriptingFunctions.exec(ScriptingFunctions.java:166)
at jdk.nashorn.internal.scripts.Script$test01.runScript(test01.js:8)
at jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:535)
at jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:209)
at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:378)
... 5 more
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(ProcessImpl.java:386)
at java.lang.ProcessImpl.start(ProcessImpl.java:137)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
... 10 more
谢谢你的详细解答。这是非常不幸的,因为我将不得不为每个我想在我的脚本中使用的shell命令准备一个'.bat'包装器。 –
那么,如果你想保持它们之间的某种状态(比如当前目录),那么它们将不会工作,因为每个'$ EXEC'都有独立的'上下文'。另外,对于单个或一小组命令,您可以像这样调用'cmd':'$ EXEC('cmd/C“dir && cd C:\ && dir'')' – sainaen
谢谢,我知道上下文在'$ EXEC's之间丢失,但绝对路径可以存储在javascript中并每次传递给命令行。我想不出任何其他国家会使用我的。 –