从脚本中获取Swift脚本的路径 [英] Get path to Swift script from within script
本文介绍了从脚本中获取Swift脚本的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在用Swift编写脚本,并且希望它修改某些始终与脚本本身存在于同一目录中的文件.有没有办法从自身内部获取脚本的路径?我试过了:
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 from within itself? I tried:
print(Process.arguments)
但这只会输出实际提供给脚本的路径,该路径可以是完全解析的路径,可以是文件名,也可以是介于两者之间的任何内容.
But that outputs only the path that was actually given to the script, which may be the fully resolved path, just the file name, or anything in between.
我打算将该脚本与swift /path/to/my/script.swift
一起运行.
I'm intending the script to be run with swift /path/to/my/script.swift
.
推荐答案
速览:
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)
}
}
这篇关于从脚本中获取Swift脚本的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文