Get path to Swift script from within script

前端 未结 2 1231
庸人自扰
庸人自扰 2021-02-19 22:46

I\'m writing a script in Swift, and I want it to modify some files that always exist in the same directory as the script itself. Is there a way to get the path to the script fro

2条回答
  •  时光说笑
    2021-02-19 23:23

    The accepted answer doesn't work in Swift 3. Also, this is a more straightforward approach:

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

    However, it has the same problem pointed out by @rob-napier, if the script's directory is in your PATH.

提交回复
热议问题