使用 NSTask 运行终端命令

发布于 2024-11-27 07:32:54 字数 853 浏览 5 评论 0原文

我想在我的程序中运行终端命令。 该命令如下所示:

cd /path/to/file/; ./foo HTTPProxy 127.0.0.1

它适用于 system(),但当我使用 NSTask 时它不起作用。

system("cd /path/to/file/; ./foo HTTPProxy 127.0.0.1");

工作正常但

NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/path/to/file/./foo"];

NSPipe *pipe = [NSPipe pipe];
[task setStandardOutput:pipe];
NSFileHandle *file = [pipe fileHandleForReading];

[task setArguments:[NSArray arrayWithObjects:@"HTTPProxy 127.0.0.1", nil]];
[task launch];

NSData *data = [file readDataToEndOfFile];
NSString *string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(string);

没有。 输出:

Command-line option 'HTTPProxy 127.0.0.1' with no value. Failing.

有人有想法吗?

I want to run a Terminal command in my program.
The command looks like this:

cd /path/to/file/; ./foo HTTPProxy 127.0.0.1

It works with system() but it doesn't work when I use NSTask.

system("cd /path/to/file/; ./foo HTTPProxy 127.0.0.1");

works fine but

NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/path/to/file/./foo"];

NSPipe *pipe = [NSPipe pipe];
[task setStandardOutput:pipe];
NSFileHandle *file = [pipe fileHandleForReading];

[task setArguments:[NSArray arrayWithObjects:@"HTTPProxy 127.0.0.1", nil]];
[task launch];

NSData *data = [file readDataToEndOfFile];
NSString *string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(string);

doesn't.
Output:

Command-line option 'HTTPProxy 127.0.0.1' with no value. Failing.

Has anybody an idea?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鼻尖触碰 2024-12-04 07:32:54

现在我想我已经明白了:

[task setArguments:[NSArray arrayWithObjects:@"HTTPProxy", @"127.0.0.1", nil]];

这些是从命令行调用中的单独参数...

旧答案:

您可以尝试设置当前执行目录:

– setCurrentDirectoryPath:

这基本上是 cd 的效果代码的系统版本。

Now I think I have got it:

[task setArguments:[NSArray arrayWithObjects:@"HTTPProxy", @"127.0.0.1", nil]];

those are separate arguments in your invocation from the command line...

OLD ANSWER:

You could trying setting the current directory for execution:

– setCurrentDirectoryPath:

This is basically the effect of cd in the system version of your code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文