【问题标题】:Get path to Swift script from within script从脚本中获取 Swift 脚本的路径
【发布时间】:2015-10-07 10:22:36
【问题描述】:

我正在用 Swift 编写一个脚本,我希望它能够修改一些始终与脚本本身位于同一目录中的文件。有没有办法从自身内部获取脚本的路径?我试过了:

print(Process.arguments)

但这仅输出实际提供给脚本的路径,可能是完全解析的路径,只是文件名,或介于两者之间的任何内容。

我打算用swift /path/to/my/script.swift 运行脚本。

【问题讨论】:

    标签: swift command-line-arguments swift2


    【解决方案1】:

    很快:

    let cwd = FileManager.default.currentDirectoryPath
    print("script run from:\n" + cwd)
    
    let script = CommandLine.arguments[0];
    print("\n\nfilepath given to script:\n" + script)
    
    //get script working dir
    if script.hasPrefix("/") { //absolute
        let path = (script as NSString).deletingLastPathComponent
        print("\n\nscript at:\n" + path)
    } else {
        let urlCwd = URL(fileURLWithPath: cwd)
        if let path = URL(string: script, relativeTo: urlCwd)?.path {
            let path = (path as NSString).deletingLastPathComponent
            print("\n\nscript at:\n" + path)
        }
    }
    

    【讨论】:

    • 注意如果使用 #! 会失败它在 PATH 中(但它确实与 OP 所说的运行脚本的方式相匹配,所以没关系)
    • @RobNapier 你是什么意思?我确实在顶部有#!/usr/bin/env swift,但那不在我的$PATH
    • 我的意思是如果 script.swift 在你的 PATH 中,那么只要调用“script.swift”就会让它看起来像是在你当前所在的任何目录中。
    【解决方案2】:

    接受的答案在 Swift 3 中不起作用。此外,这是一种更直接的方法:

    import Foundation
    
    let currentDirectoryURL = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
    let url = URL(fileURLWithPath: CommandLine.arguments[1], relativeTo: currentDirectoryURL)
    print("script at: " + url.path)
    

    但是,如果脚本的目录在您的 PATH 中,它会遇到 @rob-napier 指出的相同问题。

    【讨论】:

    • 这在 Swift 3 中几乎可以完美运行,但 CommandLine.arguments[0] 包含脚本名称(在 Zev 的问题中)。你想要CommandLine.arguments[1],它将包含传递的路径/脚本的名称。
    猜你喜欢
    • 2011-01-10
    • 2011-07-15
    • 1970-01-01
    • 2018-04-13
    • 1970-01-01
    • 1970-01-01
    • 2011-08-16
    • 2013-12-05
    • 1970-01-01
    相关资源
    最近更新 更多