yihui / knitr

A general-purpose tool for dynamic report generation in R
https://yihui.org/knitr/
2.39k stars 878 forks source link

Use knitr::purl() to export Python files (.py) #1928

Open GitHunter0 opened 3 years ago

GitHunter0 commented 3 years ago

Hey @yihui , purl() has being an incredibly useful function for me.

Since RStudio editor for .py files is still limited (no code sections and no outline pane), I mostly use R Notebooks to write Python code.

Is it possible to make purl() to export .py files as well, so that we can later source it via reticulate::source_python()?

It would be very handy.

Thank you very much

yihui commented 3 years ago

Yes, I hope to improve this in the future, but I don't yet know how. If all code chunks are from the same language (e.g. python), the answer would be obvious. If a document contains multiple types of code chunks, it will be tricky.

From what you are saying above, I feel you would be okay with each python code chunk being written into a separate .py file, and the purl() output (which is an R script) will call reticulate::source_python() to run these .py files?

Thanks!

GitHunter0 commented 3 years ago

Actually, handling the most simple case would suffice to me, i.e., take one .Rmd file with only Python chunks and convert it into one single .py file (so that I can call reticulate::source_python())

Thanks for the feedback!

GitHunter0 commented 1 year ago

Closing as it is being tracked by https://github.com/yihui/knitr/issues/2209

cderv commented 1 year ago

Oops sorry I missed this. Let's keep this one.

GitHunter0 commented 1 year ago

In the conversion to .py files, my suggestion is to mark python chunks with #%% , since this is interpreted as code cells by Spyder and VScode IDEs.

yihui commented 1 year ago

Do you mean something like this?

#%% label, chunk options ----------
code

I looked at the code and thought a little about the implementation yesterday. The tricky part is that I need to check if all code chunks are python beforehand. This isn't hard for a single document. For a document that contains child documents, knitr doesn't parse child documents in advance, so it's not possible to know if child documents contain other languages. I guess this edge case should be relatively rare, though.

GitHunter0 commented 1 year ago

Do you mean something like this?

#%% label, chunk options ----------
code

Yes @yihui , that's what I mean.

I guess this edge case should be relatively rare, though.

I also believe this case should be rare, I would not worry much about that.

cderv commented 1 year ago

Could we limit the feature to document that does not use child document ?

By emitting an error if child document is detected and explaining the function does not support it ?

I agree this should be rare!

GitHunter0 commented 1 year ago

We could also allow files that use child documents but throw a warning message explaining the limitation every time a child is detected.