簡體   English   中英

NSTask 輸出到列表中

[英]NSTask output into a list

我嘗試使用 NSTask 列出目錄中的文件/文件夾,如何將每一行中的輸出放入列表中? 我嘗試打印出來,它只顯示第一行。

NSTask * list = [[NSTask alloc] init];
[list setLaunchPath:@"/bin/ls"];
[list setCurrentDirectoryPath:@"/"];

NSPipe * out = [NSPipe pipe];
[list setStandardOutput:out];

[list launch];
[list waitUntilExit];

NSFileHandle * read = [out fileHandleForReading];
NSData * dataRead = [read readDataToEndOfFile];
NSString * stringRead = [[NSString alloc] initWithData:dataRead encoding:NSUTF8StringEncoding]];
HBLogDebug(@"PATH: %@", stringRead); //Only the first line printed

NSMutableArray *outputlist = [[NSMutableArray alloc] init];

//This part here I'm not so sure how to proceed since it's only one line, I expected multiples line
for (NSString *s in stringRead?dataRead?){
    [outputlist addObject:s];
}

提前致謝!

在此處的評論之后是一個在 Xcode 中構建的工作示例。 runCommand方法基於此答案更新並可選使用waitUntilExit因此您可以看到不使用它不會凍結應用程序。

@implementation AppDelegate

// Arguments:
//    atPath: full pathname of executable
//    arguments: array of arguments to pass, or nil if none
// Return:
//    the standard output, or nil if any error
//
// This method blocks the caller until the called command completes
// (due to both readDataToEndOfFile & waitUntilExit)
// If this an issue either run on a thread or use the asynchronous read alternatives to readDataToEndOfFile
// If there is no need to check terminatation status the waitUntilExit and terminationStatus can be skipped
// by defining RUN_COMMAND_CHECK_TERMINATION as 0

#define RUN_COMMAND_CHECK_TERMINATION 0

+ (NSString *) runCommand:(NSString *)atPath withArguments:(nullable NSArray *)arguments
{
   NSTask *task = [NSTask new];
   NSPipe *pipe = [NSPipe new];

   task.standardOutput = pipe;     // pipe standard output

   task.launchPath = atPath;       // set path
   if(arguments)
      task.arguments = arguments;  // set arguments

   [task launch];                  // execute

   NSData *data = pipe.fileHandleForReading.readDataToEndOfFile; // read standard output

#if RUN_COMMAND_CHECK_TERMINATION
   [task waitUntilExit];           // verify process has exited to prevent terminationStatus faulting
                                   // must do this *after* read otherwise if pipe fills wait can block forever

   if (task.terminationStatus != 0) // check termination status & have output
      return nil;
#endif

   if (data == nil) // check termination status & have output
      return nil;

   return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; // return stdout as string
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
   NSString *stringRead =  [AppDelegate runCommand:@"/bin/ls" withArguments:@[@"/"]];
   NSLog(@"PATH: %@", stringRead);
   NSArray *outputList = [stringRead componentsSeparatedByString:@"\n"]; // Note: will produce an empty last line, removing that is left as an exercise
   NSLog(@"Lines: %@", outputList);
}

@end

如果您的代碼凍結到HBLogDebug一些奇怪的HBLogDebug (因為上面使用NSLog )或您的代碼中的其他東西,您將不得不找出來。

HTH

1.使用NSLog代替HBLogDebug

`NSLog(@"PATH: %@", stringRead); //it prints all lines in my case`
  1. 按換行符拆分 stringRead

    for (NSString *s in [stringRead componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]){ [outputlist addObject:s]; }

  2. 在 Objective-c 中為 MACOS 列出文件的更好方法

    [[NSFileManager defaultManager] contentsOfDirectoryAtPath:@"<path>" error:nil]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM