简体   繁体   中英

How should I preferably "run" Python scripts in RStudio? Through run (using reticulate::repl_python()?) or source?

I just started to use RStudio with Python (up to now everything works) and I wonder if there is a preferred way to run scripts such as my small Test.py containing

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)

There is an answer for R here but this does not consider Python. I tried the flollowing:

  1. Source (Ctrl + Shift + S) from R-console => R-console is used

在此处输入图像描述

  1. Start Python console using reticulate::repl_python() in R-console => Change from R- to Python-console

在此处输入图像描述

  1. Source (Ctrl + Shift + S) from Python-console => Change from Python- to R-console

在此处输入图像描述

It seems, reticulate::repl_python() forces the quit first.

  1. Run lines or a selection using "run" (Ctrl + Enter) => Starts Python-console and stays there

在此处输入图像描述


This reference for reticulate and its description did not help : The reticulate package provides a comprehensive set of tools for interoperability between Python and R... Reticulate embeds a Python session within your R session, enabling seamless, high-performance interoperability.

In the RStudio IDE there should be a "Source script" button (keyboard shortcut on a Mac: shift-cmd-S) which sources the script.

在此处输入图像描述

From the terminal this is then how it looks:

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

(Too long for a comment. Maybe it helps others and hopefully, everything is correct)

What I understand now, RStudio provides an editor for R (not surprising). When you run Python code within RStudio, there is an R-wrapper for Python translating the code to R.

Thus, RStudio does not switch the editor to a native Python-IDE (which was my expectation) like VScode or others.

What I understand now: If you have projects with Python only, use a Python editor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM