swift - How to run terminal command in swift from any directory?
问题描述
I'm trying to creating a macOS application that that involves allowing the user to run terminal commands. I am able to run a command, but it runs from a directory inside my app, as far as I can tell. Running pwd
returns /Users/<me>/Library/Containers/<My app's bundle identifier>/Data
.
How can I chose what directory the command runs from?
I'm also looking for a way to get cd
to work, but if I can chose what directory to run the terminal command from, I can handle cd
manually.
Here is the code that I'm currently using to run terminal commands:
func shell(_ command: String) -> String {
let task = Process()
let pipe = Pipe()
task.standardOutput = pipe
task.arguments = ["-c", command]
task.launchPath = "/bin/zsh"
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)!
return output
}
I'm using Xcode 12 on Big Sur.
Thanks!
解决方案
上有一个已弃用的属性 currentDirectoryPath
。Process
假设您不想使用已弃用的属性,请在阅读其文档后转到FileManager
并查看管理当前目录及其含义的规定。
或者只是cd
按照您的考虑使用 - 您正在启动一个zsh
带有shell 命令行作为参数的 shell ( )。命令行可以包含多个用分号分隔的命令,因此您可以将 acd
添加到您的command
值中。
后一种方法避免更改当前进程的当前目录。
高温高压
推荐阅读
- python - 如何从 Python 中的列表中获取前三个元素?(元音)
- angular - Angular 12 - 使用类作为 http observable
- python - 使用python与动态列合并邮件
- android - yarn android 错误“您必须为 Maven 存储库指定 URL”但它已经设置了吗?
- java - 如何使用gmail api获取访问令牌-Java,spring Boot
- javascript - ReactJS - 替换/过期日期卡
- html - 如何显示 flex css 实际工作(引导程序)
- javascript - 仅从 Javascript 中的随机范围中选择与所需总和匹配的值
- java - 斐波那契数列 - 如何计算前 100 个偶数斐波那契数的总和?
- python - 在 sqlalchemy 和烧瓶中获取上个月的数据