I'm trying to spawn a child process to run a python script from Node. I have the following request that comes in:
/webcrawler?source=http://www.pygamers.com&method=BFS&nodeCount=3&depth=0&keyword=game
I have verified that my params are coming in correctly. Here is my code set up to handle the request in app.js
:
app.get('/webcrawler', function(req, res){
var python = require('child_process').spawn(
'python',
["WebCrawler/Webcrawler.py"
, req.query.source
, req.query.method
, req.query.nodeCount
, req.query.depth
, req.query.keyword]
);
var output = "";
python.stdout.on('data', function(data){ output += data });
python.on('close', function(code){
if (code !== 0) {
return res.send(500, code);
}
return res.send(200, output);
});
});
I am calling my Python script, Webcrawler.py
which is in the WebCrawler directory. The WebCrawler directory is in the same directory as app.js
.
However, this request is giving me a 500, and I haven't been able to figure out why. It seems like I must be generating the child process incorrectly. I used this answer as a model for doing so.
它必须是绝对路径,例如/home/username/Webcrawler/webcrawler.py
Sounds like a path problem. Also checkout python-shell package. Makes your life so much easier.
you can check this package on npm- native-python
it provides a very simple and powerful way to run python functions from node might solve your problem. import { runFunction } from '@guydev/native-python'
const example = async () => {
const input = [1,[1,2,3],{'foo':'bar'}]
const { error, data } = await runFunction('/path/to/file.py','hello_world', '/path/to/python', input)
// error will be null if no error occured.
if (error) {
console.log('Error: ', error)
}
else {
console.log('Success: ', data)
// prints data or null if function has no return value
}
}
python module
# module: file.py
def hello_world(a,b,c):
print( type(a), a)
# <class 'int'>, 1
print(type(b),b)
# <class 'list'>, [1,2,3]
print(type(c),c)
# <class 'dict'>, {'foo':'bar'}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.