Dev Fellow
Dev Fellow

Reputation: 1

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.

The problem I'm having is when I execute my nodecozmo.py script from the command like it works perfectly. When I execute the exact same script from my node app, its giving me a syntax error when it executes the py.

Not sure how this could be a syntax error, maybe python-shell package somehow uses an older Python version? 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

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');
  });

Upvotes: 0

Views: 765

Answers (1)

unutbu
unutbu

Reputation: 879113

Your python script is using type hinting which is a new syntax introduced in Python 3.5. The def statement

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.

Since your script, nodecozmo.py, runs without errors from the command line, you must be running it with a version of Python >= 3.5.

Since NodeJS returns a SyntaxError, NodeJS must be running the script Python version < 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):

Upvotes: 1

Related Questions