diff --git a/start.py b/start.py index a473ebd199..fc36fa5b8c 100755 --- a/start.py +++ b/start.py @@ -1,8 +1,7 @@ -#!/usr/bin/env python +#!/usr/bin/env python2 from __future__ import print_function - import pygtk import gtk pygtk.require('2.0') diff --git a/sw/airborne/modules/loggers/logger_uart_parse.py b/sw/airborne/modules/loggers/logger_uart_parse.py index 49083bbcdc..b7a05dd64d 100755 --- a/sw/airborne/modules/loggers/logger_uart_parse.py +++ b/sw/airborne/modules/loggers/logger_uart_parse.py @@ -1,3 +1,5 @@ +#! /usr/bin/env python + import struct with open('uart_log.bin', 'rb') as data: diff --git a/sw/ground_segment/python/fc_rotor/fc_rotor.py b/sw/ground_segment/python/fc_rotor/fc_rotor.py index 6d9d737507..374114ce78 100755 --- a/sw/ground_segment/python/fc_rotor/fc_rotor.py +++ b/sw/ground_segment/python/fc_rotor/fc_rotor.py @@ -24,11 +24,13 @@ Formation Control for Rotorcraft, remotly piloted from ground with a Joystick ''' +from __future__ import print_function import sys import numpy as np import json from time import sleep from os import path, getenv + PPRZ_HOME = getenv("PAPARAZZI_HOME", path.normpath(path.join(path.dirname(path.abspath(__file__)), '../../../../'))) sys.path.append(PPRZ_HOME + "/var/lib/python/") from pprzlink.ivy import IvyMessagesInterface @@ -183,7 +185,7 @@ class FormationControl: print("The state msg of rotorcraft ", rc.id, " stopped") sys.stdout.flush() ready = False - if rc.initialized and 'geo_fence' in self.config.keys(): + if rc.initialized and 'geo_fence' in list(self.config.keys()): geo_fence = self.config['geo_fence'] if not self.ignore_geo_fence: if (rc.X[0] < geo_fence['x_min'] or rc.X[0] > geo_fence['x_max'] @@ -251,7 +253,7 @@ class FormationControl: #print "Positions: " + str(X).replace('[','').replace(']','') #print "Velocities: " + str(V).replace('[','').replace(']','') #print "Acceleration command: " + str(U).replace('[','').replace(']','') - print "Error distances: " + str(E).replace('[','').replace(']','') + print("Error distances: " + str(E).replace('[','').replace(']','')) sys.stdout.flush() i = 0 diff --git a/sw/ground_segment/python/joystick/ivydanger.py b/sw/ground_segment/python/joystick/ivydanger.py index edc216f474..fb3d8882ba 100755 --- a/sw/ground_segment/python/joystick/ivydanger.py +++ b/sw/ground_segment/python/joystick/ivydanger.py @@ -1,5 +1,6 @@ #! /usr/bin/env python +from __future__ import print_function from arduino_dangerboard import arduino_dangerboard from ivy.std_api import * import logging @@ -63,7 +64,7 @@ where \t-s S1:S2:S3 | --sliders=S1:S2:S3 where S1, S2, S3 are the names of the slider settings to send \t-p PORT | --port=PORT where PORT is the name of the serial port for the slider box ''' - print fmt % lpathitem[-1] + print(fmt % lpathitem[-1]) def GetOptions(): # Map dangerboard sliders to these settings from aircraft settings diff --git a/sw/ground_segment/python/udp_link/datalink_to_w5100.py b/sw/ground_segment/python/udp_link/datalink_to_w5100.py index 1166b440da..4088ee7485 100755 --- a/sw/ground_segment/python/udp_link/datalink_to_w5100.py +++ b/sw/ground_segment/python/udp_link/datalink_to_w5100.py @@ -1,5 +1,6 @@ #!/usr/bin/python +from __future__ import print_function import os import sys import socket @@ -33,11 +34,11 @@ while( 1 ): format = 'B' * (len(data)) strdata = struct.unpack( format, data ) - print len( strdata ), ":", strdata + print(len( strdata ), ":", strdata) # send the command destsock.sendto( data, (options.dest_addr, options.dest_port) ) - except socket.error, e: - print 'Exception', e + except socket.error as e: + print('Exception', e) diff --git a/sw/ground_segment/python/udp_link/proxy_udp_multicast_to_link.py b/sw/ground_segment/python/udp_link/proxy_udp_multicast_to_link.py index c685c15e49..f5ca46c8a2 100755 --- a/sw/ground_segment/python/udp_link/proxy_udp_multicast_to_link.py +++ b/sw/ground_segment/python/udp_link/proxy_udp_multicast_to_link.py @@ -1,5 +1,6 @@ #!/usr/bin/python +from __future__ import print_function import os import socket import struct @@ -39,6 +40,6 @@ while( 1 ): # send the command destsock.sendto( data, (options.dest_addr, options.dest_port) ) - except socket.error, e: - print 'Exception', e + except socket.error as e: + print('Exception', e) diff --git a/sw/ground_segment/tmtc/pprzlink_proxy.py b/sw/ground_segment/tmtc/pprzlink_proxy.py index 9c3ab1345c..0593642fa9 100755 --- a/sw/ground_segment/tmtc/pprzlink_proxy.py +++ b/sw/ground_segment/tmtc/pprzlink_proxy.py @@ -201,7 +201,7 @@ if __name__ == '__main__': try: proxy = Proxy(gcs_conf, acs, args.verbose) proxy.run() - except ValueError, e: + except ValueError as e: print(e) diff --git a/sw/logalizer/sdlogger_get_setting_id.py b/sw/logalizer/sdlogger_get_setting_id.py index ab6b631212..9b50560f6e 100755 --- a/sw/logalizer/sdlogger_get_setting_id.py +++ b/sw/logalizer/sdlogger_get_setting_id.py @@ -1,4 +1,6 @@ #!/usr/bin/env python + +from __future__ import print_function import sys from os import path, getenv @@ -12,4 +14,4 @@ if __name__ == '__main__': ac_id = int(sys.argv[1]) command_name = sys.argv[2] settings = PaparazziACSettings(ac_id) - print settings.name_lookup[command_name].index + print(settings.name_lookup[command_name].index) diff --git a/sw/misc/attitude_reference/pat/utils.py b/sw/misc/attitude_reference/pat/utils.py index 814555e591..ba89a65011 100644 --- a/sw/misc/attitude_reference/pat/utils.py +++ b/sw/misc/attitude_reference/pat/utils.py @@ -20,6 +20,7 @@ """ Utility functions """ +from __future__ import print_function import math import numpy as np import numpy.linalg as linalg @@ -216,7 +217,7 @@ def num_jacobian(X, U, P, dyn): dx = dX[i, :] delta_f = dyn(X + dx / 2, 0, U, P) - dyn(X - dx / 2, 0, U, P) delta_f = delta_f / dx[i] - # print delta_f + # print(delta_f) A[:, i] = delta_f epsilonU = (0.1 * np.ones(i_size)).tolist() @@ -243,12 +244,12 @@ def saturate(V, Sats): def print_lti_dynamics(A, B, txt=None, print_original_form=False, print_modal_form=False): if txt: - print txt + print(txt) if print_original_form: - print "A\n", A - print "B\n", B + print("A\n", A) + print("B\n", B) w, M = np.linalg.eig(A) - print "modes \n", w + print("modes \n", w) if print_modal_form: # print "eigen vectors\n", M # invM = np.linalg.inv(M) @@ -256,4 +257,4 @@ def print_lti_dynamics(A, B, txt=None, print_original_form=False, print_modal_fo # Amod = np.dot(np.dot(invM, A), M) # print "Amod\n", Amod for i in range(len(w)): - print w[i], "->", M[:, i] + print(w[i], "->", M[:, i]) diff --git a/sw/simulator/mesonh/mesonh.py b/sw/simulator/mesonh/mesonh.py index 1e2c8ad271..fd91b4e1f4 100755 --- a/sw/simulator/mesonh/mesonh.py +++ b/sw/simulator/mesonh/mesonh.py @@ -1,3 +1,5 @@ +#!/usr/bin/env python + from __future__ import absolute_import, print_function, division from mesonh_atmosphere import MesoNHAtmosphere import os diff --git a/sw/tools/airframe_editor/airframe_editor.py b/sw/tools/airframe_editor/airframe_editor.py index f59e54e476..a53f32d58b 100755 --- a/sw/tools/airframe_editor/airframe_editor.py +++ b/sw/tools/airframe_editor/airframe_editor.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python2 from __future__ import print_function diff --git a/sw/tools/airframe_editor/gui_dialogs.py b/sw/tools/airframe_editor/gui_dialogs.py index 2a0ca5e731..a281668d0c 100644 --- a/sw/tools/airframe_editor/gui_dialogs.py +++ b/sw/tools/airframe_editor/gui_dialogs.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python2 from __future__ import print_function diff --git a/sw/tools/iridium/iridium_link.py b/sw/tools/iridium/iridium_link.py index 9555407ced..9daac9edf5 100755 --- a/sw/tools/iridium/iridium_link.py +++ b/sw/tools/iridium/iridium_link.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python2 # # Copyright (C) 2016 TU Delft # diff --git a/sw/tools/parrot/parrot_utils.py b/sw/tools/parrot/parrot_utils.py index daae1b63c2..e7522f43c5 100644 --- a/sw/tools/parrot/parrot_utils.py +++ b/sw/tools/parrot/parrot_utils.py @@ -21,6 +21,8 @@ # from __future__ import print_function +from __future__ import unicode_literals +from builtins import bytes import socket import telnetlib import os @@ -103,7 +105,7 @@ class ParrotUtils: self.tn = telnetlib.Telnet(self.address, timeout=3) self.ftp = FTP(self.address) self.ftp.login() - self.tn.read_until(self.prompt) + self.tn.read_until(bytes(self.prompt, 'utf-8')) return True except: print('Could not connect to the ' + self.uav_name + ' (address: ' + self.address + ')') @@ -121,11 +123,11 @@ class ParrotUtils: # Execute a command def execute_command(self, command): - self.tn.write(command + '\n') - s = self.tn.read_until(self.prompt) - if s.endswith('[JS] $ '): + self.tn.write(bytes(command + '\n', 'utf-8')) + s = self.tn.read_until(bytes(self.prompt, 'utf-8')) + if s.endswith(b'[JS] $ '): s = s[len(command) + 2:-8] - elif s.endswith('[RS.edu] $ '): + elif s.endswith(b'[RS.edu] $ '): s = s[len(command) + 2:-12] else: s = s[len(command) + 2:-4] @@ -262,9 +264,9 @@ class ParrotUtils: # Make the upload directory and upload the file self.create_directory(self.upload_path + folder) if len(folder) > 0: - self.upload(folder + '/' + f[1], file(name, "rb")) + self.upload(folder + '/' + f[1], open(name, "rb")) else: - self.upload(f[1], file(name, "rb")) + self.upload(f[1], open(name, "rb")) sleep(0.5) print('Succesfully uploaded "' + name + '" to folder "' + folder + '"') @@ -384,6 +386,3 @@ class ParrotUtils: self.disconnect() return True - - - diff --git a/sw/tools/px4/set_target.py b/sw/tools/px4/set_target.py index 1194a4ca7d..01f425eac5 100755 --- a/sw/tools/px4/set_target.py +++ b/sw/tools/px4/set_target.py @@ -1,4 +1,6 @@ #!/usr/bin/env python + +from __future__ import print_function import os import sys import serial @@ -8,8 +10,8 @@ import time target = sys.argv[1] firmware_file = sys.argv[2] -print "Target: " + target -print "Firmware file: " + firmware_file +print("Target: " + target) +print("Firmware file: " + firmware_file) # test if pprz cdm is connected mode = -1 @@ -21,7 +23,7 @@ try: port = glob.glob(port)[0] ser = serial.Serial(port, timeout=0.5) mode = 1 - print ("Paparazzi CDC device found at port: " + port) + print("Paparazzi CDC device found at port: " + port) except (serial.serialutil.SerialException, IndexError): print("No Paparazzi CDC device found, looking further.") @@ -38,14 +40,12 @@ if mode == 1: if target == "fbw": try: c = ser.read(7) - print ("AP responded with: " + c) + print("AP responded with: " + c) if c == "TIMEOUT": - print( - "Error: FBW bootloader TIMEOUT. Power cycle the board and wait between 10 seconds to 20 seconds to retry.") + print("Error: FBW bootloader TIMEOUT. Power cycle the board and wait between 10 seconds to 20 seconds to retry.") sys.exit(1) elif c != "FBWOKOK": - print( - "Error: unknown error. Power cycle the board and wait between 10 seconds to 20 seconds to retry.") + print("Error: unknown error. Power cycle the board and wait between 10 seconds to 20 seconds to retry.") sys.exit(1) except serial.serialutil.SerialException: pass @@ -64,7 +64,7 @@ if mode == -1: # no pprz cdc was found, look for PX4 ser = serial.Serial(p, timeout=0.5) port = p mode = 2 - print ("Original PX4 firmware CDC device found at port: " + port) + print("Original PX4 firmware CDC device found at port: " + port) except serial.serialutil.SerialException: print("Non working PX4 port found, continuing...") diff --git a/sw/tools/stm32loader/stm32loader.py b/sw/tools/stm32loader/stm32loader.py index fe64de11f2..29f42a6d37 100755 --- a/sw/tools/stm32loader/stm32loader.py +++ b/sw/tools/stm32loader/stm32loader.py @@ -22,6 +22,7 @@ # along with stm32loader; see the file COPYING3. If not see # . +from __future__ import print_function import sys, getopt import serial import time @@ -37,7 +38,7 @@ QUIET = 20 def mdebug(level, message): if(QUIET >= level): - print >> sys.stderr , message + print(message, file=sys.stderr) class CmdException(Exception): @@ -300,12 +301,12 @@ class CommandInterface: - def __init__(self) : + def __init__(self) : pass def usage(): - print """Usage: %s [-hqVewvr] [-l length] [-p port] [-b baud] [-a addr] [file.bin] + print("""Usage: %s [-hqVewvr] [-l length] [-p port] [-b baud] [-a addr] [file.bin] -h This help -q Quiet -V Verbose @@ -320,7 +321,7 @@ def usage(): ./stm32loader.py -e -w -v example/main.bin - """ % sys.argv[0] + """ % sys.argv[0]) if __name__ == "__main__": @@ -329,7 +330,7 @@ if __name__ == "__main__": try: import psyco psyco.full() - print "Using Psyco..." + print("Using Psyco...") except ImportError: pass @@ -347,9 +348,9 @@ if __name__ == "__main__": try: opts, args = getopt.getopt(sys.argv[1:], "hqVewvrp:b:a:l:") - except getopt.GetoptError, err: + except getopt.GetoptError as err: # print help information and exit: - print str(err) # will print something like "option -a not recognized" + print(str(err)) # will print something like "option -a not recognized" usage() sys.exit(2) @@ -389,7 +390,7 @@ if __name__ == "__main__": try: cmd.initChip() except: - print "Can't init. Ensure that BOOT0 is enabled and reset device" + print("Can't init. Ensure that BOOT0 is enabled and reset device") bootversion = cmd.cmdGet() @@ -413,13 +414,13 @@ if __name__ == "__main__": if conf['verify']: verify = cmd.readMemory(conf['address'], len(data)) if(data == verify): - print "Verification OK" + print("Verification OK") else: - print "Verification FAILED" - print str(len(data)) + ' vs ' + str(len(verify)) + print("Verification FAILED") + print(str(len(data)) + ' vs ' + str(len(verify))) for i in xrange(0, len(data)): if data[i] != verify[i]: - print hex(i) + ': ' + hex(data[i]) + ' vs ' + hex(verify[i]) + print(hex(i) + ': ' + hex(data[i]) + ' vs ' + hex(verify[i])) if not conf['write'] and conf['read']: rdata = cmd.readMemory(conf['address'], conf['len']) diff --git a/tests/test_python3_compatibility.py b/tests/test_python3_compatibility.py new file mode 100755 index 0000000000..67a5e34c1b --- /dev/null +++ b/tests/test_python3_compatibility.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 + +import os +import ast +import sys + +def test_source_code_compatible(code_data): + try: + return ast.parse(code_data) + except SyntaxError as exc: + return False + +paparazzi_home = os.getenv("PAPARAZZI_HOME", os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../'))) + +for root, dirs, files in os.walk(paparazzi_home): + for f in files: + file = os.path.join(root, f) + if file.endswith('.py') and os.access(file, os.X_OK) and file.find('ext') == -1 and file.find('test_python3_compatibility.py') == -1: + if 'pygtk' in open(file).read(): + print("%s uses pygtk which is not be Python3 compatible" % (file)) + ast_tree = test_source_code_compatible(open(file).read()) + if not ast_tree: + print("%s might not be Python3 compatible" % (file)) + +input("Press Enter to continue with trying to run scripts, many will not work simply due to bad inputs...") +for root, dirs, files in os.walk(paparazzi_home): + for f in files: + file = os.path.join(root, f) + if file.endswith('.py') and os.access(file, os.X_OK) and file.find('ext') == -1 and file.find('test_python3_compatibility.py') == -1: + print("\n\nTesting " + file) + os.system('python3 ' + file) +