Coder Social home page Coder Social logo

Comments (5)

Durgaprasad-Budhwani avatar Durgaprasad-Budhwani commented on June 5, 2024 1

Tackling the issue where you're unable to call Python code from your Next.js application, I've got a great solution that should clear up the confusion and have your application communicating with Python in no time! The key here is to switch from using exec to spawn, which is a bit more flexible and suited for your needs. Here's how you can do it:

export const pythonExec = async () => {
  const { spawn } = require('child_process');
  console.log("I am called");
  return new Promise((resolve, reject) => {
    const pyprog = spawn('python', ["/path/to/the/code/sample-script.py"]);
    
    pyprog.stdout.on('data', function(data) {
      console.log(data.toString());
      resolve(data.toString());
    });

    pyprog.stderr.on('data', (data) => {
      console.log(data.toString());
      reject(data.toString());
    });
  });
};

This approach uses spawn from the child_process module, providing a neat, promise-based solution to asynchronously execute your Python script and handle both success and error cases. Just remember to replace "/path/to/the/code/sample-script.py" with the absolute path to your Python script. Absolute paths ensure that your Python code is correctly located and executed, regardless of where your Next.js app is running.

Also, to make sure your Python script is included in your Next.js build, consider using the copy-webpack-plugin in your next.config.js file. This plugin will help you copy your Python code into the build directory, making deployment smoother and more reliable. Here's a quick example of how you might set it up:

const CopyPlugin = require('copy-webpack-plugin');

module.exports = {
  webpack: (config, { isServer }) => {
    if (!isServer) {
      config.plugins.push(
        new CopyPlugin({
          patterns: [
            { from: 'path/to/the/code', to: 'destination/path' },
          ],
        }),
      );
    }
    return config;
  },
};

Just adjust path/to/the/code and destination/path to match your project's structure. This little tweak ensures your Python script is right where it needs to be, ready to be called by your Next.js app. Keep up the great work, and I'm here if you have any more questions or need further assistance!



"Let's make the digital world smaller! Connect with me across the web on these social platforms and let's create, share, and inspire together." ✨🌐 #StayConnected

LinkedIn Twitter

Solved 05

from next.js.

zheng-liu-seattle avatar zheng-liu-seattle commented on June 5, 2024
module.exports = {
  webpack: (config, { isServer }) => {
    if (!isServer) {
      config.plugins.push(
        new CopyPlugin({
          patterns: [
            { from: 'path/to/the/code', to: 'destination/path' },
          ],
        }),
      );
    }
    return config;
  },
};

Thanks for the details!

I have two questions:

  1. In my local, I need to use command "Python3" instead of "Python" to make it work, if I deploy it to Vercel, should I use "Python" as your code?
  2. I can tell the file path in my local, but I have no idea about the file path should look like on vercel, any clue?

Thanks!!

from next.js.

zheng-liu-seattle avatar zheng-liu-seattle commented on June 5, 2024

The vercel log says, it seems can't find python cmd, how to resolve it? @Durgaprasad-Budhwani Durgaprasad-Budhwani

{"errorType":"Error","errorMessage":"spawn python ENOENT","code":"ENOENT","errno":-2,"syscall":"spawn python","path":"python","spawnargs":["sample-script.py"],"stack":["Error: spawn python ENOENT"," at ChildProcess._handle.onexit (node:internal/child_process:286:19)"," at onErrorNT (node:internal/child_process:484:16)"," at process.processTicksAndRejections (node:internal/process/task_queues:82:21)"]}
Unknown application error occurred
Runtime.Unknown

from next.js.

Durgaprasad-Budhwani avatar Durgaprasad-Budhwani commented on June 5, 2024

Seems like Vercel only supports only one runtime for an API, either Python or NodeJS.
I am not able to get the exact example of using both the runtime.

from next.js.

cysbyte avatar cysbyte commented on June 5, 2024

The vercel log says, it seems can't find python cmd, how to resolve it? @Durgaprasad-Budhwani Durgaprasad-Budhwani

{"errorType":"Error","errorMessage":"spawn python ENOENT","code":"ENOENT","errno":-2,"syscall":"spawn python","path":"python","spawnargs":["sample-script.py"],"stack":["Error: spawn python ENOENT"," at ChildProcess._handle.onexit (node:internal/child_process:286:19)"," at onErrorNT (node:internal/child_process:484:16)"," at process.processTicksAndRejections (node:internal/process/task_queues:82:21)"]} Unknown application error occurred Runtime.Unknown

I encountered the same problem, have no idea what the exact path of the python file is after deployed on vercel.

from next.js.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.