Zev*_*erg 10 command-line-arguments swift swift2
我正在Swift中编写一个脚本,我希望它能够修改一些与脚本本身始终存在于同一目录中的文件.有没有办法从内部获取脚本的路径?我试过了:
print(Process.arguments)
Run Code Online (Sandbox Code Playgroud)
但是,它只输出实际给予脚本的路径,该路径可能是完全解析的路径,只是文件名,或者介于两者之间的任何内容.
我打算运行脚本swift /path/to/my/script.swift.
接受的答案在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指出的同样问题.
很快:
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)