繁体   English   中英

使用 python 运行 shell 命令

[英]Run a shell command with python

我正在使用两个带有 pi 3 的串行设备/模块:APC220 无线电通信模块和一个 GPS 模块,它们都通过 UART 工作。

因此,为了让这两个在同一串行总线上工作,我需要从 python 程序运行 shell 命令。

#!/usr/bin/env python

from sys import argv
import requests
import subprocess
import os

from timeit import default_timer as timer
import time
import serial
import board
import busio
import gps

from adafruit_bus_device.i2c_device import I2CDevice
import adafruit_bmp280
import adafruit_veml6070

import RPi.GPIO as GPIO

GPIO.setmode (GPIO.BCM)

GPIO.setup (4, GPIO.OUT)
GPIO.setup (17, GPIO.OUT)

GPIO.output (4, GPIO.HIGH)
GPIO.output (17, GPIO.HIGH)

i2c = busio.I2C(board.SCL, board.SDA)
bmp280 = adafruit_bmp280.Adafruit_BMP280_I2C(i2c)
uv = adafruit_veml6070.VEML6070(i2c)

# APC220 definitions
def def_serialAPC():
    # Now I need to kill gpsd so I can send the values via APC
    **subprocess.run(['sudo', 'killall', 'gpsd'])**

    ser = serial.Serial(
            port='/dev/ttyS0',
            baudrate = 9600,
            parity=serial.PARITY_NONE,
            stopbits=serial.STOPBITS_ONE,
            bytesize=serial.EIGHTBITS,
            timeout=1
    )
     ser.write(("Temperatura: %0.2f\n"%(bmp280.temperature)).encode('utf-8'))
     ser.write(("Pressao: %0.2f\n"%(bmp280.pressure)).encode('utf-8'))
     
    # Now I must start gpsd so I can read form GPS again
    **subprocess.run(["sudo", "gpsd","/dev/ttyS0 -F /var/run/gpsd.sock"])**

# change this to match the location's pressure (hPa) at sea level
bmp280.sea_level_pressure = 1013.25

#Listen on port 2947 of gpsd
# Before the GPS starts I need to run: "gpsd /dev/ttyS0 -F /var/run/gpsd.sock

**subprocess.run(["sudo", "gpsd","/dev/ttyS0 -F /var/run/gpsd.sock"])**

session = gps.gps("localhost", "2947")
session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE)

while True:
    rep = session.next()
    try :
        if (rep["class"] == "TPV") :
            print(str(rep.lat) + "," + str(rep.lon))
    except Exception as e :
        print("Got exception " + str(e))

    # Call de_serialAPC function so I can send GPS, temperature and pressure values
    def_serialAPC()
    time.sleep(1)

我无法让它工作,因为它在执行子进程的命令时“冻结”

做这个的最好方式是什么?

谢谢


编辑

按照我做了以下更正:

# APC220 definitions
def def_serialAPC():

    print("IN APC")

    # Now I need to kill gpsd so I can send the values via APC
    **subprocess.run(['sudo', 'killall', 'gpsd'])**

    ser = serial.Serial(
            port='/dev/ttyS0',
            baudrate = 9600,
            parity=serial.PARITY_NONE,
            stopbits=serial.STOPBITS_ONE,
            bytesize=serial.EIGHTBITS,
            timeout=1
    )
     ser.write(("Temperatura: %0.2f\n"% bmp280.temperature)).encode('utf-8'))
     ser.write(("Pressao: %0.2f\n"%(bmp280.pressure)).encode('utf-8'))

     print("OUT APC")
     
    # Now I must start gpsd so I can read form GPS again
    **subprocess.run(["sudo", "gpsd","/dev/ttyS0", "-F", "/var/run/gpsd.sock"])**

# change this to match the location's pressure (hPa) at sea level
bmp280.sea_level_pressure = 1013.25

#Listen on port 2947 of gpsd
# Before the GPS starts I need to run: "gpsd /dev/ttyS0 -F /var/run/gpsd.sock

**subprocess.run(["sudo", "gpsd","/dev/ttyS0 -F /var/run/gpsd.sock"])**

print("gpsd ok")

session = gps.gps("localhost", "2947")
session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE)

while True:
    print("Inside True")
    rep = session.next()
    print("After next")
    try :
        if (rep["class"] == "TPV") :
            print(str(rep.lat) + "," + str(rep.lon))
    except Exception as e :
        print("Got exception " + str(e))

    # Call de_serialAPC function so I can send GPS, temperature and pressure values
    def_serialAPC()
    time.sleep(1)

错误是:

gpsd OK
Inside True
after next
IN APC
gpsd:ERROR: can't bind to local socket var/run/gpsd.sock
gpsd:ERROR: control socket create failed, netlib error -1
OUT APC
Inside True
after next
IN APC
gpsd: no process found
gpsd:ERROR: can't bind to local socket var/run/gpsd.sock
gpsd:ERROR: control socket create failed, netlib error -1
OUT APC
Inside True
after next
IN APC
gpsd: no process found
gpsd:ERROR: can't bind to local socket var/run/gpsd.sock
gpsd:ERROR: control socket create failed, netlib error -1
OUT APC
Inside True
Traceback (most recent call last):
  File "write_test.py", line 60, in <module>
    rep = session.next()
  File "/usr/local/lib/python3.7/dist-packages/gps/gps.py", line 301, in next
    return self.__next__()
  File "/usr/local/lib/python3.7/dist-packages/gps/gps.py", line 293, in __next__
    raise StopIteration
StopIteration

但是,如果我评论所有子进程并在新终端中运行命令 gps 工作

不要将 arguments 组合成单个字符串,然后需要是单独的列表元素。

subprocess.run(["sudo", "gpsd", "/dev/ttyS0", "-F", "/var/run/gpsd.sock"])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM