【问题标题】:NSTask and arguments when running command line tools运行命令行工具时的 NSTask 和参数
【发布时间】:2011-12-03 00:29:04
【问题描述】:

如何在这段代码中将参数(在本例中为主机)传递给 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];

【问题讨论】:

    标签: cocoa nstask


    【解决方案1】:

    使用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];
    

    【讨论】:

      【解决方案2】:

      你的论点不正确。首先,您应该将启动路径设置为 /bin/ping,或者任务所在的任何位置,然后参数应该是您通常在命令行中输入的参数的 array,但随后那里用空格隔开..

      请查看本教程Wrapping UNIX commands,了解有关如何正确执行此操作的更多信息。

      【讨论】:

        【解决方案3】:
        NSMutableArray *args = [NSMutableArray array];
        NSArray *args = [NSArray arrayWithObjects:@"-c", @"\"ping -c 5", host, @"\"",nil]
        [task setArguments:args];
        

        Bash -c 需要将您的命令放在引号中。

        【讨论】:

          猜你喜欢
          • 2011-08-07
          • 1970-01-01
          • 1970-01-01
          • 2015-03-26
          • 1970-01-01
          • 2017-06-16
          • 2011-10-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多