【问题标题】:is there a way to get path and name of the interpreter that is running current script?有没有办法获取正在运行当前脚本的解释器的路径和名称?
【发布时间】:2014-09-17 16:51:58
【问题描述】:

我的意思是当 lua 不是作为嵌入到另一个应用程序中而是作为独立的脚本语言运行时的情况。

我在 python 中需要PHP_BINARYsys.executable 之类的东西。使用 LUA 可以吗?

【问题讨论】:

    标签: lua


    【解决方案1】:

    请注意,lhf 给出的解决方案并不是最通用的。如果使用附加命令行参数调用了解释器(如果可能是您的情况),则必须搜索 arg

    通常,解释器名称存储在为arg 定义的最大负整数索引处。请参阅此测试脚本:

    local i_min = 0
    while arg[ i_min ] do i_min = i_min - 1 end
    i_min = i_min + 1   -- so that i_min is the lowest int index for which arg is not nil
    
    for i = i_min, #arg do
        print( string.format( "arg[%d] = %s", i, arg[ i ] ) )
    end
    

    【讨论】:

      【解决方案2】:

      试试arg[-1]。但是注意arg在Lua交互执行的时候是没有定义的。

      【讨论】:

        【解决方案3】:

        如果包含你的 Lua 解释器的目录在你的 PATH 环境变量中,并且你通过它的文件名调用了 Lua 解释器:

        lua myprog.lua
        

        那么arg[-1]包含“lua”,而不是Lua解释器的绝对路径。

        以下 Lua 程序适用于 z/OS UNIX:

        -- Print the path of the Lua interpreter running this program
        
        posix = require("posix")
        stringx = require("pl.stringx")
        
        -- Returns output from system command, trimmed
        function system(cmd)
          local f = assert(io.popen(cmd, "r"))
          local s = assert(f:read("*a"))
          f:close()
          return stringx.strip(s)
        end
        
        -- Get process ID of current process
        -- (the Lua interpreter running this Lua program)
        local pid = posix.getpid("pid")
        
        -- Get the "command" (path) of the executable program for this process
        local path = system("ps -o comm= -p " .. pid)
        
        -- Is the path a symlink?
        local symlink = posix.readlink(path)
        
        if symlink then
          print("Path (a symlink): " .. path)
          print("Symlink refers to: " .. symlink)
        else
          print("Path (actual file, not a symlink): " .. path)
        end
        

        或者,在具有 proc 文件系统的 UNIX 操作系统上,您可以使用 readlink("/proc/self/exe") 获取路径。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2010-11-25
          • 2011-07-08
          • 1970-01-01
          • 1970-01-01
          • 2020-10-20
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多