Is there a way to transfer an array of strings and integers from JavaScript to Python 3.8?

I have reviewed similar questions but haven't found a solution that works for me.

My inquiry is regarding the following code snippet:

function pyInput(){
    const buffers = [];

    proc.stdout.on('data', (chunk) => buffers.push(chunk));
    proc.stdout.on('end', () => {
        const result = JSON.parse(Buffer.concat(buffers));
        console.log('Python process exited, result:', result);
    });
    proc.stdin.write(JSON.stringify([['a','b',1],['b','c',-6],['c','a',4],['b','d',5],['d','a', -10]]));
    proc.stdin.end();


}

The python function I'm attempting to utilize is as follows:

def createGraph(listOfAttr):


    for i in range(len(listOfAttr)):

        G.add_edge(listOfAttr[i][0], listOfAttr[i][1], weight = listOfAttr[i][2])

    
#createGraph([['a','b',1],['b','c',-6],['c','a',4],['b','d',5],['d','a', -10]])

my_list = json.load(sys.stdin)
json.dump(my_list,sys.stdout)

This code aims to identify negative cycles in a graph, with the intention to input data from node js. However, my python program seems to get stuck and does not complete execution. Currently, I am refraining from passing the list from Node to the python function, but I am trying to at least display it to verify if it's being transmitted correctly.

Answer №1

The issue likely stems from using json.load() with sys.stdin. Since sys.stdin is a pipe, it remains open until explicitly closed, causing it to continuously wait for new data. One possible solution is to utilize input() to temporarily hold the stream until receiving specific input indicating the end, at which point you can proceed. Additionally, make sure to update your node.js script to send each piece of data as a separate line terminated by \n, and trigger the specified end signal once processing is complete.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying a single result in Angular from JSON without using the ng-repeat filter

Currently, I am working on developing an app to display news updates from a JSON API. The issue I am facing is that loading all the data from the JSON and filtering it using ng-repeat is causing slow performance, as there is a large amount of data. I woul ...

No data found in the request body despite using a body parser

My issue is that both req.body and req.query are empty, even though I am using body parser. I have searched for similar questions but none of the solutions seem to work for me. Here is the HTML form code: <form id="signup" action='/users/signup& ...

Pulling data from a MySQL database using AJAX and PHP to convert it into a JavaScript variable, resulting in

I am attempting to retrieve MySQL data using PHP, convert it to JSON, and then pass it into my JS variables for Chart.js. The JSON generated by PHP appears correct. However, when trying to access the data within my variables, the console is displaying them ...

How do I use Matplotlib to generate a circle with random x-axis distortions?

I am looking to create a circle that is intentionally imperfect, with varying radii at different points around the circumference in order to achieve a desired deformation effect. Here is an example image showcasing a circle with one such deformation: htt ...

The socket.on() function is not able to receive any data

I am encountering an issue with implementing socket.on functionality $('#showmsg').click(function() { var socket = io.connect('http://localhost:3000'); var msgText = $('#msgtext'); socket.emit('show msg', msgText.va ...

Populating a Dual ListBox with JSON data

I'm currently using a dual listbox control from and am attempting to populate it with information retrieved from a JSON request. Initially, I populated the Duallistbox using a VB sub like this: Public Shared Sub GenerateDropDownListAndValues(dt As ...

Converting ExpressJS Function for Multipart Uploading to AWS Lambda

Looking for advice on converting this Express.js function to AWS Lambda for Node.js 18. const upload = multer() // Write received chunk to S3 bucket app.post('/upload', upload.single("file"), (req, res) => { const { index, fileNam ...

Utilize Pygame for managing animations in the context of an MVC architecture

Currently, I am working on integrating an MVC design pattern into my Python and Pygame project. One issue I'm facing is how to effectively manage animations. For example, let's consider a scenario where we have a model object that can perform att ...

Unable to extract encrypted email from site

Is it possible to retrieve emails from this particular website, even though they seem to be protected? Although the emails are visible on the site, an encoded email appears when attempting to scrape them. My scraping attempts yielded this result: <a hr ...

Encountering issues with installing the firebase-admin pip package for Python Django on the Apple M1 chip platform

Issue with Installing firebase-admin on Apple M1 Chip System System Setup Details Operating System: macOS Big Sur (11.2.2) Chip: Apple M1 Python Version: 3.9.2 Pip Version: 20.0.1 Django: 3.1.7 I created a virtual environment for my project following ...

Establish a connection between the Discord Bot and a different channel

I need help with my Discord bot that should redirect someone to a different channel when they mention certain trigger word(s). I feel like there might be a missing line or two of code that I need to add to make it work properly. bot.on("message", messag ...

Transform JSON to Avro using Apache NiFi

Is there a way to convert JSON to Avro in Apache NiFi? For example, if I retrieve JSON using the getTwitter processor? Older versions seem to have supported a ConvertJSONToAvro processor. It appears that nowadays, the recommended approach is to use the c ...

Utilizing Jade templates for building a dynamic website with Node.js and Express

When working with a Jade template, how do you apply it? The example on the Jade website only demonstrates the conversion from Jade to HTML, but does not explain the process of actually implementing this transformation. Do you need to save the file with a s ...

Error message: Django encountering a broken pipe due to AJAX POST request

Broken pipes occur due to conflicting requests, preventing the POST request from processing. In this case, two requests are being sent: Ajax Post redirect to /message.html Adding event.preventDefault() may resolve this issue. However, implementing prev ...

Is there a way to utilize placeholders after sending buttons to users simultaneously?

While working with a Python Telegram bot, I utilized the following code to create a placeholder and reply markup. However, I noticed that it doesn't work in Telethon. reply_keyboard = [ ['test'] ] reply_keyboard_markup = Repl ...

Error! The JSON parsing encountered an unexpected exclamation mark at the beginning, causing an issue with parsing near the code snippet `!function(){var a="/...`

I'm encountering a problem during the npm installation process for my node project. I have attempted to clear the npm cache and even downgraded the node version, but the error persists. node - v14.17.6 npm - 6.14.8 npm WARN deprecated <a href="/cd ...

Attempting to utilize MarkLogic's JSON XQuery functionality for querying purposes is unfortunately not successful

After loading Twitter's JSON search output into Marklogic and transforming it into Marklogic's JSON XML format using the basic transformer, I encountered an issue when trying to query for the id. The XQuery snippet used for querying is as follow ...

What is it about the setTimeout function that allows it to not block other

Why is setTimeout considered non-blocking even though it is synchronous? And on which thread does it run if not the main thread? ...

Receiving the error message "Unable to locate the module named 'distutils'" while attempting to execute my program

My Selenium bot works perfectly on my local Mac, but when I try to run it on a virtual Windows 10 machine through Google Cloud, I encounter the following errors: "Traceback (most recent call last): File "c:\Users\ahamed_a_1235\in ...

Haven't quite got the hang of extracting NLTK POS tags using key and values yet

I am currently working with a list of names that I need to POS tag using NLTK. To make things more challenging, the names are jumbled up like thisisme which requires me to use wordsegment. After successfully POS tagging these names using a loop, I encount ...