How to install Python packages in a Node project?

Hi!

First post here, please go easy on me, my terminology and understanding is way off.
I started a Node-Python hybrid because I was not able to find how to run a Python HTTP server.

I managed to cut the core of the app down to this (server.js):

app.get( "/", ( request, response ) => {
  var pythonProcess = spawn( "python3", [ "script.py", request.headers[ "youtube-url" ] ] );
  pythonProcess.stdout.on( "data", ( data ) => {
    response.send( data );
  } );
} ).listen( process.env.PORT, () => { console.log( "Listening..." ) } );

However, this not being a Python app (no start.sh or requirements.txt) I’m not sure how to install the Python packages I need, and ideally have the app check if the package is up-to-date when a HTTP request is made, updating the package if needed.

I imagine I can temporarily add a start.sh and requirements.txt just to install the packages, then remove them afterwards, but this feels too hacky. And I could technically call pip from within the script, but this is not recommended.

Any ideas?

1 Like

I don’t know if package.json has a way of running multiple scripts on start, so I can run a start.sh (or a differently named .sh file) and after that is finished server.js runs? Though perhaps this would slow down the response time if the app has just woken up - but that’s not an issue for me.

I believe I have managed to do it that way:

-I created a file dependencies.sh where pip is updated and the rest will be installed
-I changed package.json to include that file in the “scripts” section as "prestart": "bash dependencies.sh"

It seems to work, I ran a test.py script at the end of the .sh file just to see if it prints before server.js logs it’s message, and it does.

I am getting an error from server.js now that the port is already being listened to, though I don’t think it’s related to what I did.

Perhaps “prestart” is not the correct place to put the .sh file, if anyone objects to that or anything else let me know, hope someone will find this helpful in the future.

EDIT: the error is gone, it was unrelated.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.