1

I am working on a webapplication in .net using razor pages in the mvvm-model. I've written a crawler/parser in Python that I need to control from my .NET-project. So I found another stackoverflow post that helps me solve this issue.

In order to keep my Python environment clean and organized, I've used a virtualenv to keep my libraries (BeautifulSoup4 and Requests) separated from my global interpreter. This all worked out the way I wanted.

However, I have reached a point where I need to connect both applications. So I put me parser in a separated folder within my .NET project. Furthermore, whenever my form is validated etc and reaches my OnPostAsync-method, it starts a process just like the above mentioned post describes.

But when I hit the submit button I can see in my console it is unable to find the correct packages in my Python application, since I am getting the famous: ImportError: No module named 'bs4'. I am aware this error is known and widely answered before, but I have a different question.

Question

I'd like to know how I fix this error with respect to my .NET-project and the virualenv. So i.e., is there a way to use or to link my virtualenv from Python in my .NET-project?

My Python-project-structure is:

/app/
  /src/    <-- Source code
  /output/ <-- Not relevant
  /tests/  <-- Not relevant
  /venv/   <-- Installed libraries
  main.py  <-- Entrypoint application
M. Douglas
  • 65
  • 2
  • 10

2 Answers2

0

If I understood your question well, you can specify which Python interpreter the script will be run with by modifying its first line, in the same way Bash does:

#!/path/to/venv/bin/python 
  • Thank you for answering. This is probably what I need. My parser is located in `root/subdir/parser/run.py`, so my virtualenv is in `root/subdir/parser/venv`. However, `#!/subdir/parser/venv/bin/python` is not working :( – M. Douglas May 21 '18 at 10:22
0

There should be a file /venv/Scripts/activate_this.py which contains code to activate the venv in the current interpreter. The docstring of the file says

Activate virtualenv for current interpreter:

Use exec(open(this_file).read(), {'__file__': this_file}).

This can be used when you must use an existing Python interpreter, not the virtualenv bin/python.

My source is in the parent directory of /venv/ so I use the following to activate my virtualenv.

import os

venv_activation_path = os.path.join(
    os.path.dirname(os.path.abspath(__file__)), 'venv', 'Scripts', 'activate_this.py')
exec(open(venv_activation_path).read(), {'__file__': venv_activation_path})
Logan
  • 35
  • 10