我该如何从我的Objective-C Cocoa应用程序中执行终端命令(例如grep
)?
我该如何从我的Objective-C Cocoa应用程序中执行终端命令(例如grep
)?
你可以使用NSTask
。下面是一个示例,运行命令'/usr/bin/grep foo bar.txt
'。
int pid = [[NSProcessInfo processInfo] processIdentifier];
NSPipe *pipe = [NSPipe pipe];
NSFileHandle *file = pipe.fileHandleForReading;
NSTask *task = [[NSTask alloc] init];
task.launchPath = @"/usr/bin/grep";
task.arguments = @[@"foo", @"bar.txt"];
task.standardOutput = pipe;
[task launch];
NSData *data = [file readDataToEndOfFile];
[file closeFile];
NSString *grepOutput = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog (@"grep returned:\n%@", grepOutput);
NSPipe
和 NSFileHandle
用于重定向任务的标准输出。如需更详细的关于在 Objective-C 应用程序中与操作系统交互的信息,请参阅苹果开发者中心上的此文档:与操作系统交互。//The magic line that keeps your log where it belongs
task.standardOutput = pipe;
这里有一个解释:https://web.archive.org/web/20141121094204/https://cocoadev.com/HowToPipeCommandsWithNSTask
NSMutableData *data = [NSMutableData dataWithCapacity:512];
。然后,while ([task isRunning]) { [data appendData:[file readDataToEndOfFile]]; }
。我"相信"在while循环结束后还应该再加上一句[data appendData:[file readDataToEndOfFile]]
。 - Davekent的文章给了我一个新想法。这个runCommand方法不需要一个脚本文件,只需通过一行命令运行:
- (NSString *)runCommand:(NSString *)commandToRun
{
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/bin/sh"];
NSArray *arguments = [NSArray arrayWithObjects:
@"-c" ,
[NSString stringWithFormat:@"%@", commandToRun],
nil];
NSLog(@"run command:%@", commandToRun);
[task setArguments:arguments];
NSPipe *pipe = [NSPipe pipe];
[task setStandardOutput:pipe];
NSFileHandle *file = [pipe fileHandleForReading];
[task launch];
NSData *data = [file readDataToEndOfFile];
NSString *output = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return output;
}
你可以这样使用这个方法:NSString *output = runCommand(@"ps -A | grep mysql");
分享精神驱动...这是我经常用来运行shell脚本的方法。 你可以将一个脚本添加到你的产品捆绑包中(在构建的复制阶段),然后在运行时读取和执行该脚本。注意:此代码会在privateFrameworks子路径中查找脚本。 警告:这可能会对部署的产品造成安全风险,但对于我们内部开发来说,这是一种简单的定制简单事物的方法(比如要将内容同步到哪个主机...),无需重新编译应用程序,只需编辑捆绑包中的shell脚本。
//------------------------------------------------------
-(void) runScript:(NSString*)scriptName
{
NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath: @"/bin/sh"];
NSArray *arguments;
NSString* newpath = [NSString stringWithFormat:@"%@/%@",[[NSBundle mainBundle] privateFrameworksPath], scriptName];
NSLog(@"shell script path: %@",newpath);
arguments = [NSArray arrayWithObjects:newpath, nil];
[task setArguments: arguments];
NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];
NSFileHandle *file;
file = [pipe fileHandleForReading];
[task launch];
NSData *data;
data = [file readDataToEndOfFile];
NSString *string;
string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog (@"script returned:\n%@", string);
}
//------------------------------------------------------
编辑:修复了NSLog的问题
如果你正在使用NSTask通过bash运行命令行工具,那么你需要包含这个“魔法”代码行以保持NSLog正常工作:
//The magic line that keeps your log where it belongs
[task setStandardInput:[NSPipe pipe]];
抱歉,我只能使用英语进行交流和回答问题。NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];
//The magic line that keeps your log where it belongs
[task setStandardInput:[NSPipe pipe]];
Swift 3.0的更改:
NSPipe
已更名为Pipe
NSTask
已更名为Process
这是基于inkit之前Objective-C的回答。他将其编写为NSString
的category —
对于Swift,它成为了String
的extension。
extension String {
func runAsCommand() -> String {
let pipe = Pipe()
let task = Process()
task.launchPath = "/bin/sh"
task.arguments = ["-c", String(format:"%@", self)]
task.standardOutput = pipe
let file = pipe.fileHandleForReading
task.launch()
if let result = NSString(data: file.readDataToEndOfFile(), encoding: String.Encoding.utf8.rawValue) {
return result as String
}
else {
return "--- Error running command - Unable to initialize string from file data ---"
}
}
}
let input = "echo hello"
let output = input.runAsCommand()
print(output) // prints "hello"
或者只需要:
print("echo hello".runAsCommand()) // prints "hello"
@IBAction func toggleFinderShowAllFiles(_ sender: AnyObject) {
var newSetting = ""
let readDefaultsCommand = "defaults read com.apple.finder AppleShowAllFiles"
let oldSetting = readDefaultsCommand.runAsCommand()
// Note: the Command results are terminated with a newline character
if (oldSetting == "0\n") { newSetting = "1" }
else { newSetting = "0" }
let writeDefaultsCommand = "defaults write com.apple.finder AppleShowAllFiles \(newSetting) ; killall Finder"
_ = writeDefaultsCommand.runAsCommand()
}
请注意,从Pipe
读取的Process
结果是一个NSString
对象。它可能是一个错误字符串,也可能是一个空字符串,但它应该始终是一个NSString
。String
并返回。NSString
,则函数将返回一个错误消息。该函数本可以编写成返回可选的String?
,但这样使用起来很笨拙,并且没有任何有用的目的,因为这种情况发生的可能性非常小。清理了顶部答案中的代码,使其更易读、更少冗余,并添加了一行方法的优点,并将其制作成了NSString类别。
@interface NSString (ShellExecution)
- (NSString*)runAsCommand;
@end
实现:
@implementation NSString (ShellExecution)
- (NSString*)runAsCommand {
NSPipe* pipe = [NSPipe pipe];
NSTask* task = [[NSTask alloc] init];
[task setLaunchPath: @"/bin/sh"];
[task setArguments:@[@"-c", [NSString stringWithFormat:@"%@", self]]];
[task setStandardOutput:pipe];
NSFileHandle* file = [pipe fileHandleForReading];
[task launch];
return [[NSString alloc] initWithData:[file readDataToEndOfFile] encoding:NSUTF8StringEncoding];
}
@end
使用方法:
NSString* output = [@"echo hello" runAsCommand];
如果您遇到输出编码问题:那么
// Had problems with `lsof` output and Japanese-named files, this fixed it
NSString* output = [@"export LANG=en_US.UTF-8;echo hello" runAsCommand];
希望它对你有用,就像对未来的我一样。 (嗨,你!)
这是一个使用 Pipe
、Process
和 String
的 Swift 示例。
extension String {
func run() -> String? {
let pipe = Pipe()
let process = Process()
process.launchPath = "/bin/sh"
process.arguments = ["-c", self]
process.standardOutput = pipe
let fileHandle = pipe.fileHandleForReading
process.launch()
return String(data: fileHandle.readDataToEndOfFile(), encoding: .utf8)
}
}
使用方法:
let output = "echo hello".run()
fork、exec和wait可以使用,如果你不是真正寻求 Objective-C 特定的方法。fork
会创建一个当前运行程序的副本,exec
将当前运行的程序替换为新的程序,wait
等待子进程退出。例如(没有任何错误检查):
#include <stdlib.h>
#include <unistd.h>
pid_t p = fork();
if (p == 0) {
/* fork returns 0 in the child process. */
execl("/other/program/to/run", "/other/program/to/run", "foo", NULL);
} else {
/* fork returns the child's PID in the parent. */
int status;
wait(&status);
/* The child has exited, and status contains the way it exited. */
}
/* The child has run and exited by the time execution gets to here. */
还有 system 函数,它会像在终端输入命令一样运行命令。这种方法更简单易用,但你对情况的掌控能力较小。
我假设你正在开发一款Mac应用程序,所以这些链接指向苹果提供的函数文档,但它们都是POSIX
规范,所以你可以在任何符合POSIX标准的系统上使用它们。
同样还有经典的POSIX system("echo -en '\007'");
我写了这个"C"函数,因为NSTask
让人感到很讨厌。
NSString * runCommand(NSString* c) {
NSString* outP; FILE *read_fp; char buffer[BUFSIZ + 1];
int chars_read; memset(buffer, '\0', sizeof(buffer));
read_fp = popen(c.UTF8String, "r");
if (read_fp != NULL) {
chars_read = fread(buffer, sizeof(char), BUFSIZ, read_fp);
if (chars_read > 0) outP = $UTF8(buffer);
pclose(read_fp);
}
return outP;
}
NSLog(@"%@", runCommand(@"ls -la /"));
total 16751
drwxrwxr-x+ 60 root wheel 2108 May 24 15:19 .
drwxrwxr-x+ 60 root wheel 2108 May 24 15:19 ..
…
为了完整/明确起见......
还有IT技术相关内容,请您提供需要翻译的具体内容。#define $UTF8(A) ((NSString*)[NSS stringWithUTF8String:A])
多年过去了,对我来说,C
仍然是一个令人困惑的混乱,而且我对于纠正上述严重缺点的能力没有太多信心 - 我唯一能提供的橄榄枝是@inket答案的简化版本,它只有最基本的要素,献给我那些追求纯粹/厌恶冗长的同行们......
id _system(id cmd) {
return !cmd ? nil : ({ NSPipe* pipe; NSTask * task;
[task = NSTask.new setValuesForKeysWithDictionary:
@{ @"launchPath" : @"/bin/sh",
@"arguments" : @[@"-c", cmd],
@"standardOutput" : pipe = NSPipe.pipe}]; [task launch];
[NSString.alloc initWithData:
pipe.fileHandleForReading.readDataToEndOfFile
encoding:NSUTF8StringEncoding]; });
}
除了上面几个出色的回答之外,我使用以下代码来处理命令输出的后台进程,并避免[file readDataToEndOfFile]
的阻塞机制。
- (void)runCommand:(NSString *)commandToRun
{
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/bin/sh"];
NSArray *arguments = [NSArray arrayWithObjects:
@"-c" ,
[NSString stringWithFormat:@"%@", commandToRun],
nil];
NSLog(@"run command:%@", commandToRun);
[task setArguments:arguments];
NSPipe *pipe = [NSPipe pipe];
[task setStandardOutput:pipe];
NSFileHandle *file = [pipe fileHandleForReading];
[task launch];
[self performSelectorInBackground:@selector(collectTaskOutput:) withObject:file];
}
- (void)collectTaskOutput:(NSFileHandle *)file
{
NSData *data;
do
{
data = [file availableData];
NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] );
} while ([data length] > 0); // [file availableData] Returns empty data when the pipe was closed
// Task has stopped
[file closeFile];
}
NSTask
已更名为Process
。 - Sam Soffes
/usr/bin
等位置的任何二进制文件,例如grep
。 - jeff-h