Python script runs in Thonny but Errors in terminal

Question:

I am able to get my script to work when I manually run it in the Thonny IDE, but I cannot trigger it in the Terminal window with

sudo python /home/pi/myscript.py

I receive this error:

Traceback (most recent call last):
  File "/home/pi/myscript.py", line 14, in <module>
    MESSAGE1_B = bytes(MESSAGE1, 'utf-8')
TypeError: str() takes at most 1 argument (2 given)

My code is as follows:

import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library
import time

GPIO.setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BOARD) # Use physical pin numbering
GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # Set pin 10 to be an input pin and set initial value to be pulled low (off)
GPIO.setup(26, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # Set pin 26 to be an input pin and set initial value to be pulled low (off)

import socket

UDP_IP = "10.1.10.149"
UDP_PORT = 50005
MESSAGE1 = "$ Channel 1 Thru 5 @ FULL #"
MESSAGE1_B = bytes(MESSAGE1, 'utf-8')
MESSAGE2 = "$ Channel 1 thru 5 @ 0 #"
MESSAGE2_B = bytes(MESSAGE2, 'utf-8')

print("UDP target IP: %s" % UDP_IP)
print("UDP target port: %s" % UDP_PORT)
print("message: %s" % MESSAGE1)
print("message: %s" % MESSAGE2)


while True: # Run forever
    if GPIO.input(10) == GPIO.HIGH:
        sock = socket.socket(socket.AF_INET, # Internet
                     socket.SOCK_DGRAM) # UDP
        sock.sendto(MESSAGE1_B, (UDP_IP, UDP_PORT)) #
        
        time.sleep(0.5)
        
    if GPIO.input(26) == GPIO.HIGH:
        sock = socket.socket(socket.AF_INET, # Internet
                     socket.SOCK_DGRAM) # UDP
        sock.sendto(MESSAGE2_B, (UDP_IP, UDP_PORT)) #
        
        time.sleep(0.5)

Can anyone help me figure out what is wrong? Please and thank you.

Asked By: Ryan Ponsell

||

Answers:

"You appear to be running your code with two different Python versions – 3.x in Thonny, 2.x in the terminal.

– jasonharper
Oct 8, 2020 at 20:49"

Answered By: Ryan Ponsell

use python3 /home/pi/myscript.py

I had similar issues until I used the same Python as Thonny

Answered By: m m
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.