我应该如何在RStudio中运行Python脚本?是通过运行(使用reticulate :: repl_python())还是source?

3

我刚开始使用RStudio和Python(目前一切正常),我想知道是否有一种首选的方法来运行脚本,例如我的小Test.py包含以下内容:

import inspect
import os

a = 5
print(a)

print(inspect.currentframe())
os.chdir("C:/.../") # a path, whatever you like
cwd = os.getcwd()
 
# print the current directory
print("Current working directory is:", cwd)

这里有一个关于R的答案,点击此处,但是它没有考虑Python。我尝试了以下操作:

  1. 在R-console中使用源代码(Ctrl + Shift + S) => 使用R-console

enter image description here

  1. 使用reticulate::repl_python()在R-console中启动Python console => 从R-切换到Python-console

enter image description here

  1. 在Python-console中使用源代码(Ctrl + Shift + S) => 从Python-切换到R-console

enter image description here

从结果来看,reticulate::repl_python()会先强制执行quit命令。

  1. 使用“run”(Ctrl + Enter)运行一行或多行代码 => 启动Python-console,并保持打开状态

enter image description here


这个关于reticulate的参考文档和它的描述没有帮助: reticulate包提供了一整套工具,用于实现Python和R之间的互操作性...... Reticulate将一个Python会话嵌入到您的R会话中,实现了无缝的高性能互操作性。

2个回答

3
在RStudio IDE中应该有一个“源代码”按钮(Mac上的键盘快捷键为shift-cmd-S),它可以对脚本进行源代码处理。

enter image description here

从终端看,它就是这个样子:

reticulate::source_python('~/Untitled.py')

那么,想法是始终在R环境中工作?Python控制台在大多数情况下未使用?如果需要调试怎么办,例如在这里(https://dev59.com/k1cP5IYBdhLWcg3wNnjW#44728031)看到的内容?(我无法使用ipdb进行调试。如果我逐行执行,当源代码也会抛出一个错误`IndexError:list index out of range时,它仍然会抛出一个错误。Error in py_run_file_impl(file, local, convert) : IndexError: list index out of range`) - Christoph
嗨@Christoph,我对RStudio IDE用于Python的更高级用法(如调试)不是很熟悉。我不确定为什么你选择了RStudio - 你同时使用R和Python吗?当涉及到R时,我喜欢它的功能,但对于Python项目,我非常喜欢VScode,我认为其中的调试功能也非常出色。 - Valeri Voev

0

(评论太长了。也许对其他人有帮助,希望一切都正确)

我现在理解的是,RStudio提供了一个R编辑器(不足为奇)。 当您在RStudio中运行Python代码时,有一个R包装器将代码转换为R。

因此,RStudio不会将编辑器切换到本机Python-IDE(这是我的期望),如VScode或其他编辑器。

我现在的理解是:如果您只使用Python进行项目,请使用Python编辑器。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接