如何在Swift 3.0中使用标准输入运行流程 [英] How to run a Process in Swift 3.0 with standard input
问题描述
使用Swift Process运行MySQL恢复转储文件时遇到问题.
I have a problem when run MySQL restore dump file with Swift Process.
let command = "/usr/local/bin/mysql -h theHost -P 3306 -u root -pTheInlinePassword example_database < dumpFile.sql"
let task = Process()
task.launchPath = "/usr/bin/env"
task.arguments = command.components(separatedBy: " ")
task.launch()
问题是Process无法理解标准输入<
.我如何使用这样的标准输入运行命令.谢谢.
The problem is Process doesn't understand standard input <
. How I can run command with standard input like this. Thanks.
更新:
let task = Process()
task.launchPath = "/usr/local/bin/mysql"
task.arguments = ["-h", "theHost", "-P", "3306", "-u", "root", "-pTheInLinePassword", "example_data"]
task.standardInput = try! FileHandle(forReadingFrom: filePath!)
task.launch()
我尝试了下面的代码.这对我有用
I tried code bellow. This works for me
推荐答案
< filename
语法是外壳程序提供的功能,不是程序本身要处理的功能.
The < filename
syntax is a feature provided by the shell, not something that programs themselves ever deal with.
处理此问题的正确方法是构造一个FileHandle
以便从dumpFile.sql
中读取,然后将该FileHandle
设置为Process
的standardInput
属性.
The proper way to handle this is to construct a FileHandle
for reading from dumpFile.sql
and then set that FileHandle
as the standardInput
property of the Process
.
作为旁注,由于您不依赖PATH查找或设置任何环境变量,因此我不知道您为什么使用/usr/bin/env
作为启动路径.
As a side note, I don't know why you're using /usr/bin/env
as your launch path, since you're not relying on PATH lookup or setting any environment variables.
let input = try FileHandle(forReadingFrom: URL(fileURLWithPath: "dumpFile.sql"))
let task = Process()
task.launchPath = "/usr/bin/mysql"
task.arguments = ["-h", "theHost", "-P", "3306", "-u", "root", "-pTheInlinePassword", "example_database"]
task.standardInput = input
task.launch()
这篇关于如何在Swift 3.0中使用标准输入运行流程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!