我试图使用Process()
在Swift中启动一个任务,但我需要查看为了调试目的发送到shell的内容.
我正在try 发送以下命令:
gswin64c.exe -q -dNODISPLAY -dNOSAFER -c "(input.pdf) (r) file runpdfbegin pdfpagecount = quit"
如果我在使用UNIX shell(bash、zsh等)的环境中运行相同的命令,那么它运行良好.在Windows中使用cmd.但是,它失败,并给出以下错误消息:
Error: /undefined in ".
我怀疑Swift 正在插入斜杠作为"转义"字符.有没有办法查看Swift发送到shell的字符串?
以下是一个示例:
import Foundation
let inputFile = URL(fileURLWithPath: "input.pdf")
let task = Process()
// In MacOS or Linux, obviously, we would use the appropriate path to 'gs'.
// Use gswin32c.exe if you have the 32-bit version of Ghostscript in Windows.
task.executableURL = URL(fileURLWithPath: #"C:\Program Files\gs\gs9.56.1\bin\gswin64c.exe"#)
// The following works when the shell is bash, zsh, or similar, but not with cmd
task.arguments = ["-q",
"-dNODISPLAY",
"-dNOSAFER",
"-c",
"\"(\(inputFile.path)) (r) file runpdfbegin pdfpagecount = quit\""]
let stdout = Pipe()
let stderr = Pipe()
task.standardOutput = stdout
task.standardError = stderr
do {
try task.run()
} catch {
print(error)
exit(1)
}
task.waitUntilExit()
extension String {
init?(pipe: Pipe) {
guard let data = try? pipe.fileHandleForReading.readToEnd() else {
return nil
}
guard let result = String(data: data, encoding: .utf8) else {
return nil
}
self = result
}
}
if let stdoutText = String(pipe: stdout) {
print(stdoutText)
}
if let stderrText = String(pipe: stderr) {
print(stderrText)
}
接下来,该命令是否可以用Swift编写,以便正确地传递给GhostScript?
跟进:
似乎没有一种直接的方法可以看出Swift 向壳牌发送了什么.
然而,我还是解决了眼前的问题.似乎是将代码发送到Windows命令shell的消毒剂在空格前插入了斜杠.我可以通过删除PostScript指令两侧的引号(事实证明它们不是必需的)并将每个元素放置在数组的一个单独成员中来解决这个问题:
task.arguments = [ "-q",
"-dNODISPLAY",
"-dNOSAFER",
"-c",
"(\(inputFile.path))",
"(r)",
"file",
"runpdfbegin",
"pdfpagecount",
"=",
"quit" ]
或者,如果您希望看到整个工作示例:
import Foundation
let inputFile = URL(fileURLWithPath: "input.pdf")
let task = Process()
// In MacOS or Linux, obviously, we would use the appropriate path to 'gs'.
// Use gswin32c.exe if you have the 32-bit version of Ghostscript in Windows.
task.executableURL = URL(fileURLWithPath: #"C:\Program Files\gs\gs9.56.1\bin\gswin64c.exe"#)
print(inputFile.path)
task.arguments = [ "-q",
"-dNODISPLAY",
"-dNOSAFER",
"-c",
"(\(inputFile.path))",
"(r)",
"file",
"runpdfbegin",
"pdfpagecount",
"=",
"quit" ]
let stdout = Pipe()
let stderr = Pipe()
task.standardOutput = stdout
task.standardError = stderr
do {
try task.run()
} catch {
print(error)
exit(1)
}
task.waitUntilExit()
extension String {
init?(pipe: Pipe) {
guard let data = try? pipe.fileHandleForReading.readToEnd() else {
return nil
}
guard let result = String(data: data, encoding: .utf8) else {
return nil
}
self = result
}
}
if let stdoutText = String(pipe: stdout) {
print(stdoutText)
}
if let stderrText = String(pipe: stderr) {
print(stderrText)
}