visual-studio-code - VS Code - 使用 Code Runner 扩展在虚拟机 (VM) 上运行程序
问题描述
我通过 Vagrant 和 Virtual Box 使用 Linux VM 在 Windows 上进行开发。我试图弄清楚如何让 Code Runner 扩展在 VM 上运行我的文件。迄今为止最大的障碍是,对于给定的文件,我需要将 Windows 主机路径转换为 Linux 来宾路径。
背景:
Code Runner扩展允许将文件类型映射到 shell 命令以运行这些文件。例如,
"java": "cd $dir && javac $fileName && java $fileNameWithoutExt"
告诉 Code Runner,当我尝试运行一个 Java 文件时,它应该cd
到包含该文件的目录,并编译该文件,然后运行编译后的文件。从文件类型到命令的映射称为code-runner.executorMap
包含在settings.json
. 通过添加选项
"code-runner.runInTerminal": true
对我settings.json
来说,我可以告诉 Code Runner 在集成终端中运行。因此,通过简单地从集成终端通过 SSH 连接到我vagrant ssh
的虚拟机,我就有了针对虚拟机的代码运行程序。
这就是问题所在 - Code Runner 正在使用我的 Windows 样式路径和我的 Windows 文件结构作为我的 VM 的命令行参数。
例如,假设我的 Windows 文件结构看起来像这样c:\a\b\c\d
,并且我的 VM 有它的根目录c
,c
并且d
是共享文件夹。如果我想在其中运行一个文件d
,该命令cd $dir
将告诉我的虚拟机去做cd c:\a\b\c\d
。
我已经想到了解决方法,例如将以下内容添加到我的设置中以运行 python 文件
"python": "cd \"$(dirname \"$(locate -l1 $fileName)\")\"; python3 $fileName",
在集成终端(VM)上运行的这个命令定位并更改到包含要运行的文件的目录。然后它告诉 python3 解释器运行该文件。但是,这并不总是有效(例如,具有相同名称的多个文件),并且需要我更新locate
依赖于每次添加文件的数据库。
必须有某种方法将我的 Windows 文件路径转换为虚拟机上的路径(例如c:\a\b\c\d
-> /c/d
)。也许通过流浪者?我将不胜感激任何帮助。
解决方案
我开发了一种解决方法。我仍然会对“更清洁”的解决方案感兴趣。
解决方法如下:
首先,我编写了一个 Python 脚本来将 Windows 路径转换为我的虚拟机上的路径。该脚本接受文件的 Windows 路径和文件名作为参数。
#pathconverter.py
import sys
windows_path=sys.argv[1]
file_name=sys.argv[2]
path_to_vagrantfile = r"C:\Users\Evan\Google Drive\Development\Vagrantfile"
slashes=path_to_vagrantfile.count("\\")
y=windows_path.split("\\")[slashes:]
linux_path="/vagrant/"+'/'.join(y) + "/" + file_name
print(linux_path)
因此,以下代码从 Windows 文件位置转换为我的虚拟机上的位置(假设您将 pathconverter.py 保存在共享目录的根目录下,\vagrant
:
python3 \"/vagrant/pathconverter.py\" $dirWithoutTrailingSlash $fileName
因此,要运行各种解释语言的大多数文件,我只需将此命令的输出作为参数提供给解释器。例如,要在我的 VM 上自动运行 Python 脚本,我只需将以下行添加到 code-runner.executorMap:
"python": "python3 \"$(python3 \"/vagrant/pathconverter.py\" $dirWithoutTrailingSlash $fileName)\""
或者对于球拍/方案,我只是这样做:
"scheme": "racket \"$(python3 \"/vagrant/pathconverter.py\" $dirWithoutTrailingSlash $fileName)\""
推荐阅读
- node.js - 使用 sequelize 为 postgres 定义具有对象数组的模型
- python - Keras 深度神经网络给出不正确/恒定的回归线
- javascript - 如何柏树等待元素的转换
- database - 如何在 Material UI 表中实现 Dynamodb 分页
- pca - 如何在具有向量元素的矩阵上进行 PCA?
- java - 添加地图框依赖时出现毕加索依赖错误
- python - Python:从减法/加法构造一个类
- python - python中的Unix时间转换
- .htaccess - 防止浏览器缓存 .htaccess 文件本身
- reactjs - 使用反应确定日期是星期六还是星期日