在R中调用fasttext命令因重定向符<执行失败的解决问询
解决R中调用fasttext含重定向命令的问题
核心问题原因
R的system()函数默认不会解析shell的重定向符(<),它会把整个命令内容直接作为参数传给fasttext程序,导致<和sentences.txt被当成无效参数,触发用法错误。
可行解决方案
1. 让system()通过shell解析命令
给system()添加shell=TRUE参数,让命令先交给shell处理重定向逻辑,再执行fasttext:
system("fasttext print-sentence-vectors model.bin < sentences.txt", shell = TRUE)
如果需要捕获输出结果,额外加上intern=TRUE:
vec_results <- system("fasttext print-sentence-vectors model.bin < sentences.txt", shell = TRUE, intern = TRUE)
2. 用system2()通过管道传递输入(跨平台更稳定)
system2()是system()的改进版,支持分离命令和参数,还能直接指定输入源,无需依赖shell重定向:
# 打开文件连接 file_conn <- file("sentences.txt", open = "r") # 将文件内容作为fasttext的标准输入 system2("fasttext", args = c("print-sentence-vectors", "model.bin"), stdin = file_conn) # 关闭文件连接 close(file_conn)
这种方式跨Windows/Linux/macOS都能正常运行,避免了shell语法的兼容性问题。
3. 解决shell()的UNC路径问题
如果必须使用shell()且不想切换目录,可通过两种方式处理UNC路径:
- 转换为短路径:
unc_path <- "\\\\server\\share\\sentences.txt" local_short_path <- shortPathName(unc_path) shell(paste0("fasttext print-sentence-vectors model.bin < ", local_short_path))
- 用双引号包裹UNC路径:
shell('fasttext print-sentence-vectors model.bin < "\\\\server\\share\\sentences.txt"')
总结
优先推荐system2()的管道输入方式,无需依赖shell语法,跨平台可靠性更高;如果习惯用shell重定向写法,给system()加上shell=TRUE即可。处理UNC路径时,转换短路径或用引号包裹就能解决报错问题。
内容的提问来源于stack exchange,提问作者astel
相关产品推荐
相关产品推荐

