docs: python 3 updates

This commit is contained in:
Oleg Kalachev
2020-10-20 11:31:16 +03:00
parent 404b42c9f9
commit 98e43aba49
20 changed files with 34 additions and 34 deletions

View File

@@ -98,9 +98,9 @@ rospy.init_node('my_node')
# ...
def markers_callback(msg):
print 'Detected markers:':
print('Detected markers:'):
for marker in msg.markers:
print 'Marker: %s' % marker
print('Marker: %s' % marker)
# Create a Subscription object. Each time a message is posted in aruco_detect/markers, the markers_callback function is called with this message as its argument.
rospy.Subscriber('aruco_detect/markers', MarkerArray, markers_callback)

View File

@@ -138,7 +138,7 @@ def image_callback(data):
(x, y, w, h) = barcode.rect
xc = x + w/2
yc = y + h/2
print ("Found {} with data {} with center at x={}, y={}".format(b_type, b_data, xc, yc))
print("Found {} with data {} with center at x={}, y={}".format(b_type, b_data, xc, yc))
image_sub = rospy.Subscriber('main_camera/image_raw', Image, image_callback, queue_size=1)

View File

@@ -39,7 +39,7 @@ cat file.py
Run `file.py` as a Python script:
```bash
python file.py
python3 file.py
```
Reboot Raspberry Pi:

View File

@@ -59,7 +59,7 @@ rospy.init_node('flight')
def range_callback(msg):
# Process data from the rangefinder
print 'Rangefinder distance:', msg.range
print('Rangefinder distance:', msg.range)
rospy.Subscriber('rangefinder/range', Range, range_callback)

View File

@@ -19,7 +19,7 @@ python3 flight.py
Python 3 has certain syntax differences in comparison with the old version. Instead of `print` *operator*:
```python
print 'Clover is the best'
print 'Clover is the best' # this won't work
```
use `print` *function*:

View File

@@ -34,10 +34,10 @@ Read more in the [GPS connection](gps.md) article.
> **Info** For studying Python programming language, see [tutorial](https://www.learnpython.org/en/Welcome).
After you've configured your positioning system, you can start writing programs for autonomous flights. Use the [SSH connection to the Raspberry Pi](ssh.md) to run your scripts. In order to run a Python script use the `python` command:
After you've configured your positioning system, you can start writing programs for autonomous flights. Use the [SSH connection to the Raspberry Pi](ssh.md) to run your scripts. In order to run a Python script use the `python3` command:
```bash
python flight.py
python3 flight.py
```
Below is a complete flight program that performs a takeoff, flies forward and lands:

View File

@@ -63,7 +63,7 @@ An example of subscription to topic `/foo`:
```python
def foo_callback(msg):
print msg.data
print(msg.data)
# Subscribing. When a message is received in topic /foo, function foo_callback will be invoked.
rospy.Subscriber('/foo', String, foo_callback)

View File

@@ -75,14 +75,14 @@ Displaying drone coordinates `x`, `y` and `z` in the local system of coordinates
```python
telemetry = get_telemetry()
print telemetry.x, telemetry.y, telemetry.z
print(telemetry.x, telemetry.y, telemetry.z)
```
Displaying drone altitude relative to [the ArUco map](aruco.md):
```python
telemetry = get_telemetry(frame_id='aruco_map')
print telemetry.z
print(telemetry.z)
```
Checking global position availability:
@@ -90,9 +90,9 @@ Checking global position availability:
```python
import math
if not math.isnan(get_telemetry().lat):
print 'Global position is available'
print('Global position is available')
else:
print 'No global position'
print('No global position')
```
Output of current telemetry (command line):
@@ -307,7 +307,7 @@ Landing the drone:
res = land()
if res.success:
print 'drone is landing'
print('drone is landing')
```
Landing the drone (command line):

View File

@@ -319,7 +319,7 @@ def flip():
rospy.loginfo('finish flip')
set_position(x=start.x, y=start.y, z=start.z, yaw=start.yaw) # finish flip
print navigate(z=2, speed=1, frame_id='body', auto_arm=True) # take off
print(navigate(z=2, speed=1, frame_id='body', auto_arm=True)) # take off
rospy.sleep(10)
rospy.loginfo('flip')

View File

@@ -83,7 +83,7 @@ pi.callback(ECHO, pigpio.FALLING_EDGE, fall)
while True:
# Reading the distance:
print read_distance()
print(read_distance())
```
@@ -104,7 +104,7 @@ def read_distance_filtered():
return numpy.median(history)
while True:
print read_distance_filtered()
print(read_distance_filtered())
```
An example of charts of initial and filtered data:

View File

@@ -110,9 +110,9 @@ rospy.init_node('my_node')
# ...
def markers_callback(msg):
print 'Detected markers:':
print('Detected markers:'):
for marker in msg.markers:
print 'Marker: %s' % marker
print('Marker: %s' % marker)
# Подписываемся. При получении сообщения в топик aruco_detect/markers будет вызвана функция markers_callback.
rospy.Subscriber('aruco_detect/markers', MarkerArray, markers_callback)

View File

@@ -140,7 +140,7 @@ def image_callback(data):
(x, y, w, h) = barcode.rect
xc = x + w/2
yc = y + h/2
print ("Found {} with data {} with center at x={}, y={}".format(b_type, b_data, xc, yc))
print("Found {} with data {} with center at x={}, y={}".format(b_type, b_data, xc, yc))
image_sub = rospy.Subscriber('main_camera/image_raw', Image, image_callback, queue_size=1)

View File

@@ -39,7 +39,7 @@ cat file.py
Запустить Python-скрипт `file.py`:
```bash
python file.py
python3 file.py
```
Перезагрузить Raspberry Pi:

View File

@@ -59,7 +59,7 @@ rospy.init_node('flight')
def range_callback(msg):
# Обработка новых данных с дальномера
print 'Rangefinder distance:', msg.range
print('Rangefinder distance:', msg.range)
rospy.Subscriber('rangefinder/range', Range, range_callback)

View File

@@ -19,7 +19,7 @@ python3 flight.py
Синтаксис языка Python 3 имеет определенные изменения по сравнения со второй версией. Вместо *оператора* `print`:
```python
print 'Clover is the best'
print 'Clover is the best' # this won't work
```
теперь используется *функция* `print`:

View File

@@ -34,10 +34,10 @@
> **Info** Для изучения языка программирования Python обращайтесь к [самоучителю](https://pythonworld.ru/samouchitel-python).
После настройки системы позиционирования становится возможным написание скриптов для автономных полетов. Для выполнения скриптов [подключитесь в Raspberry Pi по SSH](ssh.md). Для того, чтобы запустить Python-скрипт, используйте команду `python`:
После настройки системы позиционирования становится возможным написание скриптов для автономных полетов. Для выполнения скриптов [подключитесь в Raspberry Pi по SSH](ssh.md). Для того, чтобы запустить Python-скрипт, используйте команду `python3`:
```bash
python flight.py
python3 flight.py
```
Пример программы для полета (взлет, пролет вперед, посадка):

View File

@@ -63,7 +63,7 @@ foo_pub.publish(data='Hello, world!') # публикуем сообщение
```python
def foo_callback(msg):
print msg.data
print(msg.data)
# Подписываемся. При получении сообщения в топик /foo будет вызвана функция foo_callback.
rospy.Subscriber('/foo', String, foo_callback)

View File

@@ -75,14 +75,14 @@ land = rospy.ServiceProxy('land', Trigger)
```python
telemetry = get_telemetry()
print telemetry.x, telemetry.y, telemetry.z
print(telemetry.x, telemetry.y, telemetry.z)
```
Вывод высоты коптера относительно [карты ArUco-меток](aruco.md):
```python
telemetry = get_telemetry(frame_id='aruco_map')
print telemetry.z
print(telemetry.z)
```
Проверка доступности глобальной позиции:
@@ -90,9 +90,9 @@ print telemetry.z
```python
import math
if not math.isnan(get_telemetry().lat):
print 'Global position is available'
print('Global position is available')
else:
print 'No global position'
print('No global position')
```
Вывод текущей телеметрии (командная строка):
@@ -307,7 +307,7 @@ set_velocity(vx=0.4, vy=0.0, vz=0, yaw=float('nan'), yaw_rate=0.4, frame_id='bod
res = land()
if res.success:
print 'Copter is landing'
print('Copter is landing')
```
Посадка коптера (командная строка):

View File

@@ -337,7 +337,7 @@ def flip():
rospy.loginfo('finish flip')
set_position(x=start.x, y=start.y, z=start.z, yaw=start.yaw) # finish flip
print navigate(z=2, speed=1, frame_id='body', auto_arm=True) # take off
print(navigate(z=2, speed=1, frame_id='body', auto_arm=True)) # take off
rospy.sleep(10)
rospy.loginfo('flip')

View File

@@ -83,7 +83,7 @@ pi.callback(ECHO, pigpio.FALLING_EDGE, fall)
while True:
# Читаем дистанцию:
print read_distance()
print(read_distance())
```
@@ -104,7 +104,7 @@ def read_distance_filtered():
return numpy.median(history)
while True:
print read_distance_filtered()
print(read_distance_filtered())
```
Пример графиков исходных и отфильтрованных данных: