【问题标题】:Saving System Profiler info in a .spx file using NSTask使用 NSTask 将系统探查器信息保存在 .spx 文件中
【发布时间】:2010-02-26 17:09:09
【问题描述】:

在 Cocoa 中,我正在尝试实现一个按钮,当用户单击该按钮时,它将捕获系统分析器报告并将其粘贴到桌面上。

代码

 NSTask *taskDebug;
NSPipe *pipeDebug;
 taskDebug = [[NSTask alloc] init];
[[NSNotificationCenter defaultCenter] addObserver:selfselector:@selector(taskFinished:)       name:NSTaskDidTerminateNotification object:taskDebug];
 [profilerButton setTitle:@"Please Wait"];
 [profilerButton setEnabled:NO];

  [taskDebug setLaunchPath: @"/usr/sbin/system_profiler"];

  NSArray *args = [NSArray arrayWithObjects:@"-xml",@"-detailLevel",@"full",@">", @" 
    ~/Desktop/Profiler.spx",nil];
  [taskDebug setArguments:args];


  [taskDebug launch];

但这不会将文件保存到桌面。有 NSArray *args = [NSArray arrayWithObjects:@"-xml",@"-detailLevel",@"full",nil] 工作,它会在控制台窗口中删除整个 sys 分析器输出。

关于为什么这不起作用或如何更好地实现这一点的任何提示?我试图避免使用 shell 脚本或 AppleScript 来获取系统分析器。如果没有任何工作,那将是我的最终选择。 提前致谢。

【问题讨论】:

    标签: cocoa nstask


    【解决方案1】:
    NSArray *args = [NSArray arrayWithObjects:@"-xml",@"-detailLevel",@"full",@">", @"~/Desktop/Profiler.spx",nil];
    

    这是行不通的,因为您没有通过 shell,而且> 是一个 shell 运算符。 (另外,~ 并不特殊,除非您使用 stringByExpandingTildeInPath 扩展它。)

    Create an NSFileHandle for writing 到 Profiler.spx 文件,确保使用完整的绝对路径,而不是波浪号缩写的路径。然后,set that NSFileHandle as the task's standard output。这本质上就是当您在其中使用 > 运算符时 shell 所做的事情。

    【讨论】:

      【解决方案2】:

      这完成了(感谢 Peter 和 Costique)

      [taskDebug setLaunchPath: @"/usr/sbin/system_profiler"];    
      NSArray *args = [NSArray arrayWithObjects:@"-xml",@"-         detailLevel",@"full",nil];
      
      
      [taskDebug setArguments:args];
      
      [[NSFileManager defaultManager] createFileAtPath: [pathToFile stringByExpandingTildeInPath] contents: nil attributes: nil];
      
      outFile = [ NSFileHandle fileHandleForWritingAtPath:[pathToFile stringByExpandingTildeInPath]];
      
      [taskDebug setStandardOutput:outFile];
      [taskDebug launch];
      

      【讨论】:

        【解决方案3】:

        创建一个 NSPipe,发送 [taskDebug setStandardOutput: myPipe] 并从管道的文件句柄中读取。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-05-15
          • 2016-03-15
          • 2010-09-08
          • 2021-04-19
          • 1970-01-01
          • 2021-07-14
          相关资源
          最近更新 更多