Windows 10 上的 WSL 允许通过 bash.exe 执行 Linux 命令和命令行工具。非常有用的是,可以从 Windows 命令行 (cmd.exe
) 调用 Linux 工具/命令,方法是将其作为参数传递给 bash.exe,如下所示:
bash.exe -c <linux command>
这非常有用,因为它应该允许基于 Windows 的脚本无缝地结合 Windows 和 Linux 工具。
不幸的是,我未能从 R 脚本调用 Linux 命令(见下文)。
0) 系统
Win10 x64 + 周年更新 + 安装 WSL
1)调用Linux命令工作的比较案例
以下所有对我有用;此处仅显示了对 ls
的示例调用。
从 windows 命令行(cmd.exe 提示符)
bash -c "ls /mnt/a"
bash -c "ls /mnt/a > /mnt/a/test.txt"
如果从 WinKey + R
启动,效果相同同样适用于
.bat
文件。它可以从编译代码中调用。我使用
ShellExecute
尝试使用 Delphi XE2 32 位和 64 位:例如,这些工作(32 位和 64 位):
ShellExecute (0, PChar('open'), PChar('cmd.exe'), PChar('/c c:\windows\system32\bash.exe -c "ls /mnt/a > /mnt/a/test.txt"'), nil, SW_SHOWNORMAL);
或(32位代码):
ShellExecute (0, PChar('open'), PChar('c:\windows\sysnative\bash.exe'), PChar('-c "ls /mnt/a > /mnt/a/test.txt"'), nil, SW_SHOWNORMAL);
或(64 位代码):
ShellExecute (0, PChar('open'), PChar('c:\windows\system32\bash.exe'), PChar('-c "ls /mnt/a > /mnt/a/test.txt"'), nil, SW_SHOWNORMAL);
所有这些似乎都有效(
ShellExecute
返回 42)。
2) 无法从 R 调用 Linux 命令 使用 R 3.3.1 x64
以下所有操作(以及我尝试过的一些类似操作)均失败,状态为 65535:
shell('c:/windows/system32/bash.exe -c "ls /mnt/a"', shell="cmd.exe", flag = "/c")
shell("ls", shell="c:/windows/system32/bash.exe", flag = "-c")
system('cmd /c c:/windows/system32/bash.exe -c "ls /mnt/a > /mnt/a/test.txt"')
system('bash -c "ls /mnt/a"')
system('c:/windows/system32/bash.exe -c "ls /mnt/a > /mnt/a/test.txt"')
3)问题
鉴于1) 下的示例有效,我发现2) 非常令人费解。我在这里遗漏了什么明显的东西吗?
我将非常感谢一个简单的例子,在 WSL 下通过 bash.exe
运行 Linux 命令。
最佳答案
您的失败示例现在应该可以在 Windows 10 Insider 版本中正常运行 >= 14951 introduced many "interop" improvements and new capabilities :
> system('bash -c "ls /"')
生成:
bin cache dev home lib media opt root sbin srv tmp var
boot data etc init lib64 mnt proc run snap sys usr
关于r - 如何在适用于 Linux 的 Windows 子系统 (WSL) 下通过 bash 从 R 执行 linux 命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38818613/