Skip to content

Commit

Permalink
Use print() function in both Python 2 and Python 3
Browse files Browse the repository at this point in the history
Legacy __print__ statements are syntax errors in Python 3 but __print()__ function works as expected in both Python 2 and Python 3.
  • Loading branch information
cclauss authored and dagar committed Sep 22, 2019
1 parent cdbe4a3 commit c18104d
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 48 deletions.
15 changes: 8 additions & 7 deletions Tools/fetch_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
\t-s\tSerial baudrate
\t-o\tOutput path
\tpath\tPath to list/fetch, if ends with "/" then directory will be fetched recursively"""
from __future__ import print_function

__author__ = "Anton Babushkin"
__version__ = "1.1"
Expand Down Expand Up @@ -82,15 +83,15 @@ def _ls_dir(ser, dir, timeout):
return res

def _get_file(ser, fn, fn_out, force, timeout):
print "Get %s:" % fn,
print("Get %s:" % fn, end=' ')
if not force:
# Check if file already exists with the same size
try:
os.stat(fn_out)
except:
pass
else:
print "already fetched, skip"
print("already fetched, skip")
return

cmd = "dumpfile " + fn
Expand All @@ -112,7 +113,7 @@ def _get_file(ser, fn, fn_out, force, timeout):
sys.stdout.write(".")
sys.stdout.flush()
fout.write(buf)
print " done"
print(" done")
fout.close()
os.rename(fn_out_part, fn_out)
else:
Expand All @@ -133,13 +134,13 @@ def _get_files_in_dir(ser, path, path_out, force, timeout):
_get_file(ser, path_fn, path_fn_out, force, timeout)

def _usage():
print """Usage: python fetch_file.py [-l] [-f] [-d device] [-s speed] [-o out_path] path
print("""Usage: python fetch_file.py [-l] [-f] [-d device] [-s speed] [-o out_path] path
\t-l\tList files
\t-f\tOverwrite existing files
\t-d\tSerial device
\t-s\tSerial baudrate
\t-o\tOutput path
\tpath\tPath to list/fetch, if ends with "/" then directory will be fetched recursively"""
\tpath\tPath to list/fetch, if ends with "/" then directory will be fetched recursively""")

def _main():
dev = "/dev/tty.usbmodem1"
Expand Down Expand Up @@ -185,7 +186,7 @@ def _main():
try:
if cmd == "ls":
# List directory
print _ls_dir_raw(ser, path, timeout)
print(_ls_dir_raw(ser, path, timeout))
elif cmd == "get":
# Get file(s)
if path.endswith("/"):
Expand All @@ -199,7 +200,7 @@ def _main():
path_out = os.path.split(path)[1]
_get_file(ser, path, os.path.split(path)[1], force, timeout)
except Exception as e:
print e
print(e)

ser.close()

Expand Down
27 changes: 14 additions & 13 deletions Tools/geotag_images_ulog.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
# Parts included from https://github.com/PX4/flight_review/


from __future__ import print_function
import os, sys, time, datetime, piexif
from pyulog import *
from pyulog.px4 import *
Expand All @@ -38,9 +39,9 @@


if(len(sys.argv)) < 3:
print "Usage: python geotag_images_ulog.py [logfile] [image dir]"
print "Example: python geotag_images_ulog.py mylog.ulg ./images"
print len(sys.argv)
print("Usage: python geotag_images_ulog.py [logfile] [image dir]")
print("Example: python geotag_images_ulog.py mylog.ulg ./images")
print(len(sys.argv))
sys.exit()

logfile = sys.argv[1]
Expand Down Expand Up @@ -189,23 +190,23 @@ def load_ulog_file(file_name):
timestamp = time.mktime(datetime.datetime.strptime(timestring, "%Y:%m:%d %H:%M:%S").timetuple())
if first == 0:
first = timestamp
print "Calibrating on",f,"as last image on",timestring
print ""
print "[filename] [offset] [trigger seq] [lat] [lng] [alt]"
print("Calibrating on",f,"as last image on",timestring)
print("")
print("[filename] [offset] [trigger seq] [lat] [lng] [alt]")

offset = first - timestamp
print(f),
print(offset),
print((f), end=' ')
print((offset), end=' ')
if not offset in offsets:
offset += 1

if not offset in offsets:
offset += 1

if offset in offsets:
print(offsets[offset]),
print(camera_capture.data['lat'][offsets[offset]]),
print(camera_capture.data['lon'][offsets[offset]]),
print((offsets[offset]), end=' ')
print((camera_capture.data['lat'][offsets[offset]]), end=' ')
print((camera_capture.data['lon'][offsets[offset]]), end=' ')
print(camera_capture.data['alt'][offsets[offset]])

lat = camera_capture.data['lat'][offsets[offset]]
Expand All @@ -232,7 +233,7 @@ def load_ulog_file(file_name):
exif_bytes = piexif.dump(exif_dict)
piexif.insert(exif_bytes, f)
else:
print "Could not georeference"
print("Could not georeference")


print "Done"
print("Done")
13 changes: 7 additions & 6 deletions Tools/run-clang-tidy.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
Compilation database setup:
http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
"""
from __future__ import print_function

import argparse
import json
Expand All @@ -54,7 +55,7 @@ def find_compilation_database(path):
result = './'
while not os.path.isfile(os.path.join(result, path)):
if os.path.realpath(result) == '/':
print 'Error: could not find compilation database.'
print('Error: could not find compilation database.')
sys.exit(1)
result += '../'
return os.path.realpath(result)
Expand Down Expand Up @@ -168,9 +169,9 @@ def main():
if args.checks:
invocation.append('-checks=' + args.checks)
invocation.append('-')
print subprocess.check_output(invocation)
print(subprocess.check_output(invocation))
except:
print >>sys.stderr, "Unable to run clang-tidy."
print("Unable to run clang-tidy.", file=sys.stderr)
sys.exit(1)

# Load the database and extract all files.
Expand Down Expand Up @@ -208,18 +209,18 @@ def main():
except KeyboardInterrupt:
# This is a sad hack. Unfortunately subprocess goes
# bonkers with ctrl-c and we start forking merrily.
print '\nCtrl-C detected, goodbye.'
print('\nCtrl-C detected, goodbye.')
if args.fix:
shutil.rmtree(tmpdir)
os.kill(0, 9)

if args.fix:
print 'Applying fixes ...'
print('Applying fixes ...')
apply_fixes(args, tmpdir)

global tidy_failures
if tidy_failures > 0:
print >>sys.stderr, "clang-tidy errors: ", tidy_failures
print("clang-tidy errors: ", tidy_failures, file=sys.stderr)
sys.exit(1)

if __name__ == '__main__':
Expand Down
43 changes: 22 additions & 21 deletions integrationtests/python_src/px4_it/dronekit/MissionCheck.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
# Settings
################################################################################################

from __future__ import print_function
connection_string = '127.0.0.1:14540'

import_mission_filename = 'VTOL_TAKEOFF.mission'
Expand Down Expand Up @@ -58,22 +59,22 @@


# Connect to the Vehicle
print "Connecting"
print("Connecting")
vehicle = connect(connection_string, wait_ready=True)

while not vehicle.system_status.state == "STANDBY" or vehicle.gps_0.fix_type < 3:
if time.time() - start_time > 20:
print "FAILED: SITL did not reach standby with GPS fix within 20 seconds"
print("FAILED: SITL did not reach standby with GPS fix within 20 seconds")
sys.exit(98)
print "Waiting for vehicle to initialise... %s " % vehicle.system_status.state
print("Waiting for vehicle to initialise... %s " % vehicle.system_status.state)
time.sleep(1)

# Display basic vehicle state
print " Type: %s" % vehicle._vehicle_type
print " Armed?: %s" % vehicle.armed
print " System status: %s" % vehicle.system_status.state
print " GPS: %s" % vehicle.gps_0
print " Alt: %s" % vehicle.location.global_relative_frame.alt
print(" Type: %s" % vehicle._vehicle_type)
print(" Armed?: %s" % vehicle.armed)
print(" System status: %s" % vehicle.system_status.state)
print(" GPS: %s" % vehicle.gps_0)
print(" Alt: %s" % vehicle.location.global_relative_frame.alt)


################################################################################################
Expand Down Expand Up @@ -106,7 +107,7 @@ def upload_mission(aFileName):
#Add new mission to vehicle
for command in missionlist:
cmds.add(command)
print ' Uploaded mission with %s items' % len(missionlist)
print(' Uploaded mission with %s items' % len(missionlist))
vehicle.commands.upload()
return missionlist

Expand All @@ -128,7 +129,7 @@ def listener(self, name, mission_current):
if (current_sequence <> mission_current.seq):
current_sequence = mission_current.seq;
current_sequence_changed = True
print 'current mission sequence: %s' % mission_current.seq
print('current mission sequence: %s' % mission_current.seq)

#Create a message listener for mission sequence number
@vehicle.on_message('EXTENDED_SYS_STATE')
Expand All @@ -152,9 +153,9 @@ def listener(self, name, home_position):

while not home_position_set:
if time.time() - start_time > 30:
print "FAILED: getting home position 30 seconds"
print("FAILED: getting home position 30 seconds")
sys.exit(98)
print "Waiting for home position..."
print("Waiting for home position...")
time.sleep(1)


Expand All @@ -172,9 +173,9 @@ def listener(self, name, home_position):

while not vehicle.system_status.state == "ACTIVE":
if time.time() - start_time > 30:
print "FAILED: vehicle did not arm within 30 seconds"
print("FAILED: vehicle did not arm within 30 seconds")
sys.exit(98)
print "Waiting for vehicle to arm..."
print("Waiting for vehicle to arm...")
time.sleep(1)


Expand All @@ -185,21 +186,21 @@ def listener(self, name, home_position):
if current_sequence > 0 and current_sequence_changed:

if missionlist[current_sequence-1].z - alt_acceptance_radius > vehicle.location.global_relative_frame.alt or missionlist[current_sequence-1].z + alt_acceptance_radius < vehicle.location.global_relative_frame.alt:
print "waypoint %s out of bounds altitude %s gps altitude: %s" % (current_sequence, missionlist[current_sequence-1].z, vehicle.location.global_relative_frame.alt)
print("waypoint %s out of bounds altitude %s gps altitude: %s" % (current_sequence, missionlist[current_sequence-1].z, vehicle.location.global_relative_frame.alt))
mission_failed = True
current_sequence_changed = False
elapsed_time = time.time() - start_time

if elapsed_time < max_execution_time:
print "Mission items have been executed"
print("Mission items have been executed")

# wait for the vehicle to have landed
while (current_landed_state != 1 and elapsed_time < max_execution_time):
time.sleep(1)
elapsed_time = time.time() - start_time

if elapsed_time < max_execution_time:
print "Vehicle has landed"
print("Vehicle has landed")

# Disarm vehicle
vehicle.armed = False
Expand All @@ -213,16 +214,16 @@ def listener(self, name, home_position):

# Validate time constraint
if elapsed_time <= max_execution_time and not mission_failed:
print "Mission succesful time elapsed %s" % elapsed_time
print("Mission succesful time elapsed %s" % elapsed_time)
sys.exit(0)

if elapsed_time > max_execution_time:
print "Mission FAILED to execute within %s seconds" % max_execution_time
print("Mission FAILED to execute within %s seconds" % max_execution_time)
sys.exit(99)

if mission_failed:
print "Mission FAILED out of bounds"
print("Mission FAILED out of bounds")
sys.exit(100)

print "Mission FAILED something strange happened"
print("Mission FAILED something strange happened")
sys.exit(101)
3 changes: 2 additions & 1 deletion src/modules/mavlink/mavlink_tests/mavlink_ftp_test_data.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import print_function
import sys
print 'Arguments: file - ' + sys.argv[1] + ', length - ' + sys.argv[2]
print('Arguments: file - ' + sys.argv[1] + ', length - ' + sys.argv[2])
file = open(sys.argv[1], 'w')
for i in range(int(sys.argv[2])):
b = bytearray([i & 0xFF])
Expand Down

0 comments on commit c18104d

Please sign in to comment.