尝试使用NSTask运行cli失败了

时间:2013-02-06 01:28:09

标签: objective-c cocoa nstask

我正在尝试在cocoa app中运行以下内容:

cat PATHTOFILE | python -mjson.tool> OUTPUTFILE

    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath: @"/bin/cat"];

    NSArray *arguments = [NSArray arrayWithObject: path];
    [task setArguments: arguments];

    NSPipe *pipe = [NSPipe pipe];
    [task setStandardOutput:pipe];
    [task launch];

    NSTask *task2 = [[NSTask alloc] init];
    [task2 setLaunchPath:@"/usr/bin/python"];
    NSArray *arguments2 = [NSArray arrayWithObject:[NSString stringWithFormat:@"-mjson.tool > %@.beautify", path]];
    [task2 setArguments:arguments2];
    [task2 setStandardInput:pipe];

    NSPipe *pipe2 = [NSPipe pipe];
    [task2 setStandardOutput:pipe2];
    [task2 launch];

但是我收到以下错误:     / usr / bin / python:不支持按文件名导入。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

似乎更像是Python错误。

/usr/bin/python -mjson.tool调用以下文件:(从终端使用时)

/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/tool.py

其内容为

""" headers..."""
import sys
import json

def main():
    if len(sys.argv) == 1:
        infile = sys.stdin
        outfile = sys.stdout
    elif len(sys.argv) == 2:
        infile = open(sys.argv[1], 'rb')
        outfile = sys.stdout
    elif len(sys.argv) == 3:
        infile = open(sys.argv[1], 'rb')
        outfile = open(sys.argv[2], 'wb')
    else:
        raise SystemExit(sys.argv[0] + " [infile [outfile]]")
    try:
        obj = json.load(infile)
    except ValueError, e:
        raise SystemExit(e)
    json.dump(obj, outfile, sort_keys=True, indent=4)
    outfile.write('\n')


if __name__ == '__main__':
    main()

您的任务无法解析这些导入语句。当然因为它不像终端那么了解,也找不到这个...... 见NSTask is not launching Python with correct path