最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

VSCode, Electron, Flask: Conflicting Python Environments when Code Run through Different Methods Suspectedly Causing ModuleNotFo

programmeradmin5浏览0评论

I am running WSL: Ubuntu through VSCode. In the terminal, I have a virtual environment, .venv, activated.

Background

I am trying to run an Electron app with Flask as its backend. I can run the Flask app independently via flask --app py/routes --debug run and have a function set up in the "main.js" file of the Electron app that lets the two run simultaneously like:

flaskProc = require('child_process').spawn('py', ['./py/routes.py']);
flaskProc.stderr.on('data', (data) => {
    console.error(`stderr: ${data}`);
});

The files are structured so that the Electron app is in the parent folder and within that folder is a folder called "py" which holds all the files for the Flask app and the ".venv" folder. For the sake of simplicity, all routes pointing to the ".venv" folder and its children will be shortened to "[...]/py/.venv/<some_child>"

The Problem

This occurs when I run the Electron app with npm start via the terminal, the Flask app runs too. When I do this, the following error is given:

stderr:     from jsonschema import validate
ModuleNotFoundError: No module named 'jsonschema'

I ran pip freeze > requirements.txt and found that "jsonschema" was, indeed, there

Attempts to Solve

I suspected that this was some error caused by installing the module wrong and added the following lines to my Flask app and ran it independently:

import sys

print("Executing in", sys.executable)
if "jsonschema" in sys.modules:
    print("JSONSchema is in the modules")
else:
    print("jsonschema isn't in the modules")

this prints:

Executing in [...]/py/.venv/bin/python3
JSONSchema is in the modules

Checking the interpreter, it had the Selected Interpreter as "[...]/py/.venv/bin/python3.10", so I changed it to python3 and restarted VSCode. I activated the virtual environment once more and ran the Flask app independently, which still pointed to python3, then ran the Electron app, which still gave an error. I checked the Interpreter again and found that while the Selected Interpreter is "[...]/py/.venv/bin/python3", the Workspace's Interpreter is still "[...]/py/.venv/bin/python3.10"

And when I tried to run pip install jsonschema and python -m pip install jsonschema, I got the following messages:

Requirement already satisfied: jsonschema in ./py/.venv/lib/python3.10/site-packages (3.2.0)
Requirement already satisfied: six>=1.11.0 in ./py/.venv/lib/python3.10/site-packages (from jsonschema) (1.17.0)
Requirement already satisfied: attrs>=17.4.0 in ./py/.venv/lib/python3.10/site-packages (from jsonschema) (25.1.0)
Requirement already satisfied: setuptools in ./py/.venv/lib/python3.10/site-packages (from jsonschema) (59.6.0)
Requirement already satisfied: pyrsistent>=0.14.0 in ./py/.venv/lib/python3.10/site-packages (from jsonschema) (0.20.0)

which say that they're installing into python3.10. This is confirmed when using python -m pip show jsonschema which states that the Location is "[...]/py/.venv/lib/python3.10/site-packages"

Edit:

Running ls -la py/.venv/bin/python* gives:

lrwxrwxrwx 1 <username> <username>  7 Feb 18 11:46 py/.venv/bin/python -> python3
lrwxrwxrwx 1 <username> <username> 16 Feb 18 11:46 py/.venv/bin/python3 -> /usr/bin/python3
lrwxrwxrwx 1 <username> <username>  7 Feb 18 11:46 py/.venv/bin/python3.10 -> python3

Which shows that /python and /python3.10 both point to "python3" while /python3 points to "/usr/bin/python3". I think that this means that python3.10 is a branch of python3, so the problem is that the "routes.py" file running in python3 can't get the jsonschema import from python3.10 because it's upstream of it? With this in mind, I tried to run: py/.venv/bin/python3 -m pip install jsonschema to install the module into python3 specifically, but got the same "Requirement already satisfied" messages as before, confusing me further.

On the recommendation of wjandrea in the comments, I tried running the print("Executing in",sys.executable) line through the Electron app, which gives:

Executing in C:\Python312\python.exe
jsonschema isn't in the modules

So that's the actual problem: For some reason, the Flask app is executing on a different interpreter when run through the Electron app than when run independently. C:\Python312\python.exe is the route for the default Python interpreter, so I changed it under the Workspace scope to point to "[...]/py/.venv/bin/python3" like the Flask sys.executable, yet nothing changed.

Looking into the setting, it states that:

The setting has also been modified in the following scopes:

- Remote
- User

So I tried to change the Remote and User Default Interpreter Paths too, but that did nothing.

Why is the Electron app not running on the right interpreter? Why is it running on C\Python312\python.exe specifically? And how do I change it to run on "[...]/py/.venv/bin/python3"?

I am running WSL: Ubuntu through VSCode. In the terminal, I have a virtual environment, .venv, activated.

Background

I am trying to run an Electron app with Flask as its backend. I can run the Flask app independently via flask --app py/routes --debug run and have a function set up in the "main.js" file of the Electron app that lets the two run simultaneously like:

flaskProc = require('child_process').spawn('py', ['./py/routes.py']);
flaskProc.stderr.on('data', (data) => {
    console.error(`stderr: ${data}`);
});

The files are structured so that the Electron app is in the parent folder and within that folder is a folder called "py" which holds all the files for the Flask app and the ".venv" folder. For the sake of simplicity, all routes pointing to the ".venv" folder and its children will be shortened to "[...]/py/.venv/<some_child>"

The Problem

This occurs when I run the Electron app with npm start via the terminal, the Flask app runs too. When I do this, the following error is given:

stderr:     from jsonschema import validate
ModuleNotFoundError: No module named 'jsonschema'

I ran pip freeze > requirements.txt and found that "jsonschema" was, indeed, there

Attempts to Solve

I suspected that this was some error caused by installing the module wrong and added the following lines to my Flask app and ran it independently:

import sys

print("Executing in", sys.executable)
if "jsonschema" in sys.modules:
    print("JSONSchema is in the modules")
else:
    print("jsonschema isn't in the modules")

this prints:

Executing in [...]/py/.venv/bin/python3
JSONSchema is in the modules

Checking the interpreter, it had the Selected Interpreter as "[...]/py/.venv/bin/python3.10", so I changed it to python3 and restarted VSCode. I activated the virtual environment once more and ran the Flask app independently, which still pointed to python3, then ran the Electron app, which still gave an error. I checked the Interpreter again and found that while the Selected Interpreter is "[...]/py/.venv/bin/python3", the Workspace's Interpreter is still "[...]/py/.venv/bin/python3.10"

And when I tried to run pip install jsonschema and python -m pip install jsonschema, I got the following messages:

Requirement already satisfied: jsonschema in ./py/.venv/lib/python3.10/site-packages (3.2.0)
Requirement already satisfied: six>=1.11.0 in ./py/.venv/lib/python3.10/site-packages (from jsonschema) (1.17.0)
Requirement already satisfied: attrs>=17.4.0 in ./py/.venv/lib/python3.10/site-packages (from jsonschema) (25.1.0)
Requirement already satisfied: setuptools in ./py/.venv/lib/python3.10/site-packages (from jsonschema) (59.6.0)
Requirement already satisfied: pyrsistent>=0.14.0 in ./py/.venv/lib/python3.10/site-packages (from jsonschema) (0.20.0)

which say that they're installing into python3.10. This is confirmed when using python -m pip show jsonschema which states that the Location is "[...]/py/.venv/lib/python3.10/site-packages"

Edit:

Running ls -la py/.venv/bin/python* gives:

lrwxrwxrwx 1 <username> <username>  7 Feb 18 11:46 py/.venv/bin/python -> python3
lrwxrwxrwx 1 <username> <username> 16 Feb 18 11:46 py/.venv/bin/python3 -> /usr/bin/python3
lrwxrwxrwx 1 <username> <username>  7 Feb 18 11:46 py/.venv/bin/python3.10 -> python3

Which shows that /python and /python3.10 both point to "python3" while /python3 points to "/usr/bin/python3". I think that this means that python3.10 is a branch of python3, so the problem is that the "routes.py" file running in python3 can't get the jsonschema import from python3.10 because it's upstream of it? With this in mind, I tried to run: py/.venv/bin/python3 -m pip install jsonschema to install the module into python3 specifically, but got the same "Requirement already satisfied" messages as before, confusing me further.

On the recommendation of wjandrea in the comments, I tried running the print("Executing in",sys.executable) line through the Electron app, which gives:

Executing in C:\Python312\python.exe
jsonschema isn't in the modules

So that's the actual problem: For some reason, the Flask app is executing on a different interpreter when run through the Electron app than when run independently. C:\Python312\python.exe is the route for the default Python interpreter, so I changed it under the Workspace scope to point to "[...]/py/.venv/bin/python3" like the Flask sys.executable, yet nothing changed.

Looking into the setting, it states that:

The setting has also been modified in the following scopes:

- Remote
- User

So I tried to change the Remote and User Default Interpreter Paths too, but that did nothing.

Why is the Electron app not running on the right interpreter? Why is it running on C\Python312\python.exe specifically? And how do I change it to run on "[...]/py/.venv/bin/python3"?

Share Improve this question edited 11 hours ago wjandrea 33.1k9 gold badges69 silver badges97 bronze badges asked yesterday user24995271user24995271 416 bronze badges 14
  • 1 what does ls -la .venv/bin/python* give you? – juanpa.arrivillaga Commented yesterday
  • 1 "and ran it independently" what does that mean? How exactly are you running everything here? – juanpa.arrivillaga Commented yesterday
  • Check out How to Ask for tips on how to write a good title. I mean, what's the confusion exactly? You can edit to change it. – wjandrea Commented yesterday
  • 1 Why are you using py (py.exe)? Correct me if I'm wrong (I don't use Windows), but that's the Windows system install of Python, not the Ubuntu venv install. You could check sys.executable from the Electron app to confirm. – wjandrea Commented 17 hours ago
  • 1 @wjandrea Oh, wait, nevermind, I get what you mean. In the spawn function of the "main.js" file. Yeah, that might be it. I'm still new to Node.js, so I'll have to figure out how to change that to work, will report back later – user24995271 Commented 12 hours ago
 |  Show 9 more comments

1 Answer 1

Reset to default 0

So the problem was with how I was spawning flaskProc in the main.js file. I was using spawn("py",[path]), simply thinking that py was used to indicate it was Python code running, however, it seems to run that code on C:\Python312\python.exe by default.

I found that I could instead set spawn to "wsl", to tell Node to run WSL commands. I then passed the path to the virtual environment and the script as arguments, so it would run both, allowing the script to run in the WSL virtual environment. That ended up looking like this:

const venvPath="./py/.venv/bin/python3"
const scriptPath='./py/routes.py'
flaskProc = require('child_process').spawn("wsl", [venvPath,scriptPath]);

And here's the full connection function in case it helps someone in the future, though I feel like this post should indicate that I am in no way an authority on this, lol:

/**
 * Connects to the Flask app
 */
let flaskProc=null;
const connectToFlask=function(){
    //test version
    const venvPath="./py/.venv/bin/python3"
    const scriptPath='./py/routes.py'
    flaskProc = require('child_process').spawn("wsl", [venvPath,scriptPath]);
    //executable version
    //flaskProc = require('child_process').execFile("routes.exe");
    flaskProc.stdout.on('data', function (data) {  
        console.log("FLASK RUNNING! data:", data.toString('utf8'));
    });
    // if can't connect
    flaskProc.on('error', (err) => {
        console.error('Failed to start Flask process:', err);
        flaskProc = null;
    });
    // when Flask errors
    flaskProc.stderr.on('data', (data) => {
        console.error(`stderr: ${data}`);
    });
    //logging data
    flaskProc.stdout.on('data', (data) => {
        console.log(`stdout: ${data}`);
    });
    // on Flask close
    flaskProc.on("close", (code)=>{
        console.log(`child process exited with code ${code}`);
        flaskProc=null;
    });
}

/**
 * Create a new BrowserWindow that's connected to Flask with index.html as its UI
 */
const createWindow = () => {
    const win = new BrowserWindow({
        width: 800,
        height: 600
    });

    connectToFlask();

    win.loadFile('index.html');
}

Thank you so much to everyone who helped out!

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论