首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将正在运行的终端输出保存为变量

将正在运行的终端输出保存为变量
EN

Unix & Linux用户
提问于 2022-04-12 07:58:22
回答 1查看 1.8K关注 0票数 0

我正在运行一个使用pyserial包的python脚本。我使用一块板来控制电机的旋转,并通过USB接口连接。

该板已编程,并可旋转的电机与给定的命令。以下是一些例子:

  1. 输入:检查电机状态的命令: H010100

产出:

代码语言:javascript
运行
复制
{
.."beambreak": [0,0,0,0,0],
.."prox": [0.003,0.003],
.."T1": [0,0],
.."T2": [0,0],
.."MT": [-1,-1]
.."test_switch": 0,
.}
  1. 输入:命令转动电机一次: H010101

输出:{“旋转”:“成功”}

任务:在‘while’循环中,如何每1分钟发送一次命令(例如,H010101),检查输出消息(例如,{“旋转”:“成功”}),并根据输出消息条件发送下一个命令。

问题:当我运行代码时,"can set“输出消息出现在linux终端/IDE控制台中,但我不知道如何将消息保存为变量并在循环条件下应用。我的意思是,要检查消息是否是同一条消息,请等待1分钟,然后再次发送H010101命令?

我还尝试在*.log或*.txt保存文件,但没有使用示例:

代码语言:javascript
运行
复制
$ python test.py >> *.txt    
$ python test.py > *.log

这是我的代码:

代码语言:javascript
运行
复制
import time
import serial


# configure the serial connections 
ser = serial.Serial(
    port='/dev/ttyUSB0',
    baudrate=115200,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS
)


while True :
    print(' Check Status')
    ser.write('H010000\n'.encode())
    status_cmd = ser.readline()
    print(status_cmd)
    
    if status_cmd === "test_switch: 0 " : #  i can't save the message as variable from  running terminal 
        time.sleep(5)
      
    # Command to rotate motor
    ser.write('H010101\n'.encode())
    # read respond of give command
    reading = ser.readline()
    print(reading)    
    
    if reading == {"Drop":"Successful"} :   # i can't save the message as variable from  running terminal 
        time.sleep(60)
        # rotate motor 
        ser.write('H010101\n'.encode())
        # read respond of give command
        reading = ser.readline()
        print(reading)
EN

回答 1

Unix & Linux用户

回答已采纳

发布于 2022-04-12 10:40:38

您可以做的第一件事是将您的函数封装到方法中(如果您愿意,也可以使用类)。

检查状态

代码语言:javascript
运行
复制
def check_status(ser):
    print('Check Status')
    ser.write('H010000\n'.encode())
    current_status = ser.readline().decode('utf-8')
    return current_status

旋转电机

代码语言:javascript
运行
复制
def rotate_motor(ser):
    print('Rotating ..')
    ser.write('H010101\n'.encode())
    rotation_status = ser.readline().decode('utf-8')
    return rotation_status

您还需要导入json作为dict加载响应。

e.g

代码语言:javascript
运行
复制
>>> import json

>>> rotation_status='{"Drop":"Successful"}'
>>> json.loads(rotation_status)
{'Drop': 'Successful'}

现在您已经准备好了这些代码片段,您可以根据结果调用它们来连续运行操作。

代码语言:javascript
运行
复制
while True:
    status = json.loads(check_status(ser))
    if status['test_switch'] == 0:
        time.sleep(5)
    
    is_rotated = json.loads(rotate_motor(ser))
    if is_rotated['Drop'] == 'Successful':
        time.sleep(60)
    else:
        print('Something went wrong')
        raise Exception(is_rotated)
票数 1
EN
页面原文内容由Unix & Linux提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://unix.stackexchange.com/questions/698828

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档