[英]How to execute Python from NodeJS. Getting “invalid syntax” in my function from python
I'm using NodeJS to fire a Python script by way of python-shell package for the cozmo api. 我正在使用NodeJS通过针对cozmo api的python-shell软件包来触发Python脚本。
The problem I'm having is when I execute my nodecozmo.py script from the command like it works perfectly. 我遇到的问题是,当我从命令执行我的nodecozmo.py脚本时,就像它运行正常一样。 When I execute the exact same script from my node app, its giving me a syntax error when it executes the py. 当我从节点应用程序执行完全相同的脚本时,执行py时会出现语法错误。
Not sure how this could be a syntax error, maybe python-shell package somehow uses an older Python version? 不确定这可能是语法错误,也许python-shell包以某种方式使用了较旧的Python版本? Maybe it doesn't understand handling that syntax? 也许它不理解该语法的处理? I tried to go through the source and couldn't see why its causing the issue. 我试图查看源代码,但看不到为什么它导致了问题。
Error 错误
Error: File "nodecozmo.py", line 16
def cozmo_program(robot: cozmo.robot.Robot):
^
SyntaxError: invalid syntax
Python Script Python脚本
import time
import cozmo
def cozmo_program(robot: cozmo.robot.Robot):
robot.move_head(-5)
time.sleep(3)
robot.drive_wheels(50, -50)
robot.move_lift(5)
time.sleep(3)
robot.move_lift(-1)
time.sleep(3)
cozmo.run_program(cozmo_program)
Node App 节点应用
var PythonShell = require('python-shell');
PythonShell.run('./nodecozmo.py', function (err) {
if (err) throw err;
console.log('finished executing');
});
Your python script is using type hinting which is a new syntax introduced in Python 3.5. 您的python脚本正在使用类型提示 ,这是Python 3.5中引入的新语法。 The def
statement def
声明
def cozmo_program(robot: cozmo.robot.Robot):
is saying that the cozmo_program
function takes one argument, robot
, which should be of type cozmo.robot.Robot
. 表示cozmo_program
函数采用一个参数robot
,其类型应为cozmo.robot.Robot
。
Since your script, nodecozmo.py, runs without errors from the command line, you must be running it with a version of Python >= 3.5. 由于您的脚本nodecozmo.py从命令行运行时没有错误,因此您必须使用Python> = 3.5的版本运行它。
Since NodeJS returns a SyntaxError, NodeJS must be running the script Python version < 3.5. 由于NodeJS返回SyntaxError,因此NodeJS必须运行脚本Python版本<3.5。 Notice how the error message points directly at the colon: 注意错误消息是如何直接指向冒号的:
Error: File "nodecozmo.py", line 16
def cozmo_program(robot: cozmo.robot.Robot):
^
SyntaxError: invalid syntax
Since type hinting is a nicety but not a necessity, you could make your script backwards compatible simply by removing the type hint: 由于类型提示是很好的,但不是必需的,因此您可以通过删除类型提示使脚本向后兼容:
Change 更改
def cozmo_program(robot: cozmo.robot.Robot):
to 至
def cozmo_program(robot):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.