Using Pandoc with Swift

☆樱花仙子☆ 提交于 2019-12-02 00:57:06

This is partly because the task's executable is set to env which itself executes pandoc; but in the meantime it loses the working directory.

The solution to this is to set launchPath to the Pandoc executable.

This is also because we have to use inputPath and outputPath in the task arguments instead of just the filenames, or to set a currentDirectoryPath for the task.

Working version 1:

func shell(args: String...) -> Int32 {
    let task = NSTask()
    task.launchPath = "/usr/local/bin/pandoc"
    task.arguments = args
    task.launch()
    task.waitUntilExit()
    return task.terminationStatus
}

and

let file = "input.txt"
let text = "\\emph{test}"

if let dir : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {

    let inputPath = dir.stringByAppendingPathComponent(file)
    let outputPath = dir.stringByAppendingPathComponent("output.txt")

    //writing
    do {
        try text.writeToFile(inputPath, atomically: false, encoding: NSUTF8StringEncoding)
        shell("-f","latex","-t","markdown", inputPath, "-o", outputPath)
    }
    catch { print(error) }

    //reading
    do {
        let inputText = try NSString(contentsOfFile: inputPath, encoding: NSUTF8StringEncoding)
        print(inputText)

        let convertedText = try NSString(contentsOfFile: outputPath, encoding: NSUTF8StringEncoding)
        print(convertedText)

    }
    catch { print(error) }
}

Working version 2:

func shell(args: String...) -> Int32 {
    let task = NSTask()
    task.launchPath = "/usr/local/bin/pandoc"
    if let dir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
        task.currentDirectoryPath = dir
    }
    task.arguments = args
    task.launch()
    task.waitUntilExit()
    return task.terminationStatus
}

and

let file = "input.txt"
let text = "\\emph{test}"

if let dir : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {

    let inputPath = dir.stringByAppendingPathComponent(file)
    let outputPath = dir.stringByAppendingPathComponent("output.txt")

    //writing
    do {
        try text.writeToFile(inputPath, atomically: false, encoding: NSUTF8StringEncoding)
        shell("-f","latex","-t","markdown","input.txt","-o","output.txt")
    }
    catch { print(error) }


    //reading
    do {
        let inputText = try NSString(contentsOfFile: inputPath, encoding: NSUTF8StringEncoding)
        print(inputText)

        let convertedText = try NSString(contentsOfFile: outputPath, encoding: NSUTF8StringEncoding)
        print(convertedText)

    }
    catch { print(error) }
}

Prints:

\emph{test}
*test*

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!