【发布时间】:2015-06-07 02:34:35
【问题描述】:
我需要在 NodeJs 中调用这个 python 脚本。
Read.py
#!/usr/bin/env python
# -*- coding: utf8 -*-
import RPi.GPIO as GPIO
import MFRC522
import signal
continue_reading = True
# Capture SIGINT for cleanup when the script is aborted
def end_read(signal,frame):
global continue_reading
print "Ctrl+C captured, ending read."
continue_reading = False
GPIO.cleanup()
# Hook the SIGINT
signal.signal(signal.SIGINT, end_read)
# Create an object of the class MFRC522
MIFAREReader = MFRC522.MFRC522()
# Welcome message
print "Welcome to the MFRC522 data read example"
print "Press Ctrl-C to stop."
# This loop keeps checking for chips. If one is near it will get the UID and authenticate
while continue_reading:
# Scan for cards
(status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)
# If a card is found
if status == MIFAREReader.MI_OK:
# Get the UID of the card
(status,uid) = MIFAREReader.MFRC522_Anticoll()
# If we have the UID, continue
if status == MIFAREReader.MI_OK:
# Print UID
print "Card read UID: "+str(uid[0])+","+str(uid[1])+","+str(uid[2])+","+str(uid[3])
# This is the default key for authentication
key = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]
# Select the scanned tag
MIFAREReader.MFRC522_SelectTag(uid)
# Authenticate
status = MIFAREReader.MFRC522_Auth(MIFAREReader.PICC_AUTHENT1A, 8, key, uid)
# Check if authenticated
if status == MIFAREReader.MI_OK:
MIFAREReader.MFRC522_Read(8)
MIFAREReader.MFRC522_StopCrypto1()
else:
print "Authentication error"
我使用了 python-shell,这里是它的 NodeJs 代码
Test.js
var PythonShell = require('python-shell');
var options = {
scriptPath: '/home/pi/gpio-admin/MFRC522-python/'
};
var pyshell = new PythonShell('Read.py',options);
pyshell.on('message', function (message) {
console.log(message);
});
但是当我运行这段代码时,我在 Node 端看不到任何东西。我认为当 python 脚本达到这个级别时会出现问题。
(status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)
因为我只是使用只有 print 语句的 while 循环运行,所以它可以工作。之后,我尝试了另一种方法来实现这一目标。但是我遇到了与上面相同的问题。这是另一种方法
AltTest.js
var python = require('child_process').spawn(
'python',
// second argument is array of parameters, e.g.:
["/home/pi/gpio-admin/MFRC522-python/Read.py"]
);
var output = "";
python.stdout.on('data', function(){
output += data ;
console.log(data);
});
python.on('close', function(code){
console.log("Here you are there...");
});
任何帮助将不胜感激
【问题讨论】:
-
PyNode 包允许调用 Python 函数并取回 JS 包。 thecodinginterface.com/blog/…
-
您可以使用
child_processnodejs 包中提供的以下函数来执行任何终端命令:exec、execSync、spawn、spawnSync
标签: javascript python node.js python-2.7 raspberry-pi