从脚本中获取Swift脚本的路径

Zev*_*erg 10 command-line-arguments swift swift2

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

print(Process.arguments)
Run Code Online (Sandbox Code Playgroud)

但是,它只输出实际给予脚本的路径,该路径可能是完全解析的路径,只是文件名,或者介于两者之间的任何内容.

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

gan*_*ogo 9

接受的答案在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)
Run Code Online (Sandbox Code Playgroud)

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


Dai*_*jan 8

很快:

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,如果使用 #! 它在 PATH 中(但它确实与 OP 所说的运行脚本的方式相匹配,所以没关系) (2认同)