knitr - error when importing python module

2019-02-16 12:24发布

问题:

I am having trouble when running the python engine in knitr. I can import some modules but not others. For example I can import numpy but not pandas.

{r, engine='python'} import pandas

I get the error.

Quitting from lines 50-51 (prepayment.Rmd) 
Error in (knit_engines$get(options$engine))(options) : 
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named pandas
Calls: <Anonymous> ... process_group.block -> call_block -> block_exec -> in_dir -> <Anonymous>
In addition: Warning message:
running command ''python'  -c 'import pandas' 2>&1' had status 1 
Execution halted

It must be something to do with system path and where I am pointing.

Normally in IPython i use

import sys
sys.path.append('/path/to/directory/')

To add paths. I don't know what the problem is.

回答1:

Use:

{python engine.path="C:/anaconda/python.exe"}
import pandas

change C:/anaconda/python.exe to your python path.



回答2:

For some reason it works a little different than in IPython

The following worked for me.

I first went into IPython and did the following

import pandas
import os
path = os.path.dirname(pandas.__file__)
Out[4]: '/Users/glendonthompson/anaconda/lib/python2.7/site-packages/pandas'

Then in Rstudio in .Rmd file I ran

```{r, engine='python'}
import sys
sys.path.append('/Users/glendonthompson/anaconda/lib/python2.7/site-packages/')
import pandas
```

Maybe its something to do with anaconda messing with my packages....

Is it also true with knitr using the python engine you have to cache otherwise it won't retain the code in previous chunks?

```{r, engine='python'}
import sys
sys.path.append('/Users/glendonthompson/anaconda/lib/python2.7/site-packages/')
```

```{r,engine = 'python'}
import pandas
```

Doesn't work....



回答3:

This happened to me too, in Atom.

Check to make sure the two files are in the same directory. Put them in the same folder or path.

Then, go into Terminal or Command Line and type

cd Downloads

(or whatever large directory the files are in). Then, type in smaller folder like: cd _____, such as cd animals. There, you can open the one file that you want to have the other file import to by typing python3 -i ____.py (file name). Make sure the file has from ___(master file) import * and you can run the code in terminal.

This should work. The problem is you can't import by running the code. Instead, you have to link the two using terminal or command line.