Monday 24 August 2020

How to put in user input from a Python script running in NodeJS using child_process?

Hi. I have a Google Chrome extension which sends the user's current mouse coordinates to the ExpressJS server (currently on localhost:3000). I use the in-built fetch to send these requests to the server. When the express server receives these coordinates from the req.body, it starts a Python script (which uses Selenium) using child_process and spawning it. The Python script needs the coordinates each time it is sent to the server. The way I try to implement this is to ask for user in a while loop, using coordinates = input("Coordinates: "). However, from the server, I am not sure how to input the coordinates sent from the server each time to the running script.My current code:server.jsconst express = require('express') const app = express() const port = 3000 var hasSpawnedPythonProcess = false var pythonProcess = null var x = 0 var y = 0 app.use(express.json()) app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*') res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); app.post('/mouse', (req, res) => { x = req.body.xCor y = req.body.yCor if (!hasSpawnedPythonProcess) { console.log("Spawn python process!") hasSpawnedPythonProcess = true const spawn = require("child_process").spawn; pythonProcess = spawn('python', ["-u", "./script.py"]); pythonProcess.stderr.on('data', (data) => { console.log(data.toString()) }) pythonProcess.stdout.on('data', (data) => { console.log(data.toString()) // Don't know how to put string for user input }) } res.send({success: true}) }) app.listen(port) script.py// import selenium libraries and sys if __name__ == "__main__": // Sets path and creates browser object // Get canvas element and other stuff coordinates = input("Coordinates (maxWidth: "+str(canvas.size["width"])+", maxHeight: "+str(canvas.size["height"])+"): ") while coordinates: xCor = int(coordinates.split(",")[0]) yCor = int(coordinates.split(",")[1]) ActionChains(browser).move_to_element_with_offset(canvas, xCor, yCor).click().perform() coordinates = input("Coordinates (maxWidth: "+str(canvas.size["width"])+", maxHeight: "+str(canvas.size["height"])+"): ")

Submitted August 25, 2020 at 12:14AM by Strikerzzs

No comments:

Post a Comment