Torch,如何使用“dofile”执行一个脚本并传入参数?

我正在我的 Linux shell 中使用 th 命令执行 Torch 脚本。该 Torch 脚本需要两个输入参数:

th torch_script.lua input_parameter1 input_parameter2

现在我想要通过 Torch shell 运行此脚本。要做到这一点,我必须使用 dofile 命令。但在这种情况下,我不知道如何传递输入参数 input_parameter1input_parameter2

在 Torch 中,如何将一些输入参数传递给 dofile 执行命令?


编辑:下面是我尝试运行的代码。我无法正确运行它,也许您能告诉我为什么

external_command.lua 内容:

local arg = arg or {...}
input_parameter = arg[1]
print("input_parameter ".. input_parameter);

在 shell 上:

$th
th> tempFunc = load "external_command.lua"
th> tempFunc("try")
[string "_RESULT={tempFunc("try")}"]:1: attempt to call global 'tempFunc' (a nil value)
stack traceback:
    [string "_RESULT={tempFunc("try")}"]:1: in main chunk
    [C]: in function 'xpcall'
    /home/davide/torch/install/share/lua/5.1/trepl/init.lua:630: in function 'repl'
    ...vide/torch/install/lib/luarocks/rocks/trepl/scm-1/bin/th:185: in main chunk
    [C]: at 0x004064d0


编辑 2:我尝试了 TonyHsu 发布的解决方案,但仍然不起作用。这是我正在做的事情。

我在名为 runfile.lua 的脚本中定义了一个函数 runfile(),其中包含以下代码:

function runfile(scriptName, input)
  opt = nil
  arg = input
  dofile(scriptName)
end

然后我将之前定义的 external_command.lua 脚本作为此函数的 scriptName 输入参数:

th> scriptName = "external_command.lua"
th> require './runfile.lua'
th> runfile(scriptName, "Hello world");

不幸的是,在这种情况下,我也会报错:

external_command.lua:4: attempt to concatenate global 'input_parameter' (a nil value)
stack traceback:
    external_command.lua:4: in main chunk
    [C]: in function 'dofile'
    /home/davide/torch/temp/runfile.lua:4: in function 'runfile'
    [string "runfile(scriptName, "Hello world");"]:1: in main chunk
    [C]: in function 'xpcall'
    /home/davide/torch/install/share/lua/5.1/trepl/init.lua:648: in function 'repl'
    ...vide/torch/install/lib/luarocks/rocks/trepl/scm-1/bin/th:185: in main chunk
[C]: at 0x004064d0
点赞
用户1190388
用户1190388

你可以使用 loadfile

local TempFunc = loadfile "torch_script.lua"
TempFunc(input_parameter1, input_parameter2)
2015-10-07 14:42:00
用户4677158
用户4677158

或许你可以先定义一个函数:

function runfile(<scriptName>, ...)
opt = nil
arg = {...}
dofile(<scriptName>)
end

接着运行:

runfile(<scriptName>,...)
2015-10-10 13:58:00
用户7596504
用户7596504

我认为技巧在于将参数传递给全局变量“args”。例如,我在external_command.lua文件中有以下内容:

-- args由调用程序设置
if not args or #args == 0 then
    print('no input_parameter')
else
    print('#args = ' .. #args, 'input_parameter: ' .. args[1])
end

然后定义runfile()函数如下所示。

function runfile(f, ...)
    local tmp = args  -- 保存原始全局变量args
    args = table.pack(...)
    dofile(f)
    args = tmp  -- 恢复args
end

我在th中对其进行了测试。结果如下所示。

th> runfile('ext_command.lua', 10)
#args = 1       input_parameter: 10
                                                                      [0.0002s]
th> runfile('ext_command.lua', 'a', 'b', 'c')
#args = 3       input_parameter: a
                                                                      [0.0002s]
2017-02-26 16:16:06