gpt4 book ai didi

cocoa - 运行命令行工具时的 NSTask 和参数

转载 作者:行者123 更新时间:2023-12-03 16:26:08 25 4
gpt4 key购买 nike

如何将参数(在本例中为主机)传递给此代码中的 NSTask?它不接受主机 NSString。例如,如果我通过 ping 传递主机值......

[NSArray arrayWithObjects:@"-c",@"ping -c 5 www.google.com",nil]

然后就可以了。但它不会单独考虑主机参数。感谢您提前提供的帮助。

task =  [[NSTask alloc] init];
[pipe release];
pipe = [[NSPipe alloc] init];
[task setStandardInput: [NSPipe pipe]];

[task setLaunchPath:@"/bin/bash"];

NSArray *args = [NSArray arrayWithObjects:@"-c",@"ping -c 5",host,nil];

[task setArguments:args];
[task setStandardOutput:pipe];
NSFileHandle *fh = [pipe fileHandleForReading];

最佳答案

使用NSString类的stringWithFormat方法

 task =  [[NSTask alloc] init];
[pipe release];
pipe = [[NSPipe alloc] init];
[task setStandardInput: [NSPipe pipe]];

[task setLaunchPath:@"path"];

NSArray *args = [NSArray arrayWithObjects:@"-c",[NSString stringWithFormat: @"%@ %@ %@ %@",@"ping",@"-c",@"5",host],nil];

[task setArguments:args];
[task setStandardOutput:pipe];
NSFileHandle *fh = [pipe fileHandleForReading];

关于cocoa - 运行命令行工具时的 NSTask 和参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8364397/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com