【问题标题】:Python method not working what i need to do?Python方法不起作用我需要做什么?
【发布时间】:2020-11-07 15:55:39
【问题描述】:

我为 Arduino UNO 编写了一个游戏手柄串行驱动程序,因此,在 Arduino IDE 中协调性很好。但是在 PySerial 最后添加 b' 和 \r\n' 。我添加了replace(),但没有任何改变...... 有代码: 导入pyautogui,系统 进口时间 导入序列

ArduinoSerial=serial.Serial('/dev/ttyUSB0',115200)  #Specify the correct COM port
time.sleep(1)                             #delay of 1 second
a = 1
while a:
    ArduinoSerial.readline()
    print(ArduinoSerial.readline());

    data=str(ArduinoSerial.readline())
    data = data.replace("\r\n", "")
    print(data)
    (x,y)=data.split(":")           # read the x and y axis data
    (X,Y)=pyautogui.position()        #read the current cursor's position
    x=int(x)
    y=int(y)
    pyautogui.moveTo(X+x,Y-y)           #move cursor to desired position

有输出:

ilyabot@ilyabot-HP-Pavilion-dv6-Notebook-PC:~/Рабочий стол$ python3 joy_driver.py 
b'0:0\r\n'
b'0:0\r\n'
Traceback (most recent call last):
  File "joy_driver.py", line 21, in <module>
    x=int(x)
ValueError: invalid literal for int() with base 10: "b'0"

【问题讨论】:

  • 请参阅this question,了解如何使用.decode() 而不是str() 将二进制字符串正确转换为常规字符串

标签: python python-3.x linux replace valueerror


【解决方案1】:

我修复了问题...发现了新问题...现在没有错误,只有空的并且什么都没有... pyautogui 想要工作:Xubuntu 18.04 x86_64 Python:Python 3.6.9

【讨论】:

    【解决方案2】:

    我修好了!

    data = data[:-5]
    

    我将 data = data.replace("\r\n'", "") 替换为 data = data[:-5] 并且它可以工作!!!

    所有代码都有:

    # Importing modules
    import pyautogui, sys
    import time 
    import serial
    # Arduino Serial-Joystick Driver
    SerialConnection=serial.Serial('/dev/ttyUSB0',115200)  # Specify the your COM port
    while 1:
        data = str(SerialConnection.readline()) # Read the x and y axis data
        data = data.replace("b'", "") # Eraing "b'"
        data = data[:-5] # Easing "\r\n'"
        (x,y)=data.split(":") # Adding ":" split
        print(data) # Logging
        (X,Y)=pyautogui.position()        # Read the current cursor's position
        x=int(x) # Converting str(x) to int(x)
        y=int(y) # Converting str(y) to int(y)
        pyautogui.moveTo(X-x,Y+y) # Move cursor to desired position
    

    【讨论】:

    • 你可以只做data = SerialConnection.readline().decode().strip()然后拆分它
    猜你喜欢
    • 1970-01-01
    • 2023-03-22
    • 2021-07-22
    • 2012-10-22
    • 2013-07-05
    • 2012-07-13
    • 1970-01-01
    • 2013-07-22
    • 2011-06-15
    相关资源
    最近更新 更多