Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import and run a python file in an rmarkdown chunk?

I have an r markdown document and a python script named sim1.py. I would like to import the python code into a chunk. In some cases I want it to run, and in other cases I just want the code pasted.

So far I've tried using the child chunk option in the following way:

```{python, child=here::here("simulations", "sim1.py"), eval=FALSE}
```

I receive no errors when I run the above code, but no output is produced.

When I run the following code

```{python, child=here::here("simulations", "sim1.py"), eval=TRUE}
```

I get an error:

You can't use `macro parameter character #' in horizontal mode.
l.1938 #
        plt.savefig("test.pdf") 

where the error is referring to a comment line.

Any ideas on how I can do both:

  • Showing just the code
  • Running the code and displaying both the code and the output

EDIT: Another option I'm trying is the following:

```{python sim-1, code=cat(readLines(sim_folder), sep = '\n'), eval=FALSE}
```

with the intention that this reads the contents of the file, pastes that content into the body of the chunk, and evaluates it using the python engine. Though in this case with eval=FALSE it would just display the file contents as valid python code. This doesn't generate an error, but it doesn't display anything either.

like image 834
Scott White Avatar asked Dec 03 '25 03:12

Scott White


1 Answers

I almost had it! The correct solution is in the documentation of all places: https://yihui.org/knitr/options/#code-chunk

```{python sim-1, code=readLines(sim_folder), eval=FALSE}
```
like image 186
Scott White Avatar answered Dec 04 '25 17:12

Scott White



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!