【问题标题】:Get Input from command line parallel to executing http request从命令行并行获取输入以执行 http 请求
【发布时间】:2021-08-18 13:00:02
【问题描述】:

在我从连接到打印机的条形码扫描仪获取输入的应用程序中,我想根据正在扫描的 ID 标记已打印的文档。

由于网络可以很慢,打印机可以很快,所以我想避免请求没有完成,程序在扫描下一个文档时无法接受新输入的情况。

我试图用线程解决这个问题,但在这一点上卡住了。我得到的只是错误:TypeError: updateOrder() missing 1 required positional argument: 'ids'

这里是完整的代码:

import requests
from requests.models import HTTPBasicAuth
import threading

# Empty Array to buffer the incoming billbeeIds 

ids = [] 

# Get the order-id from the scanner

def getInput():
    while True: 
        newId = str(input("BillBeeId eingeben"))
        ids.append(newId)

# Mark order-id as printed

def updateOrder(ids):
    while len(ids) > 0:
        billbeeId = ids.pop(0)
        response = requests.post(
            'https://app.billbee.io/api/v1/orders/{0}/tags'.format(billbeeId),
            auth=HTTPBasicAuth('xxx', 'xxx'),
            headers={'X-Billbee-Api-Key': 'xxx'},
            json={
                "Tags": [
                    "Lieferschein-Gedruckt"
                ]
            }
        )
        print(response)   

t1 = threading.Thread(target=getInput)
t2 = threading.Thread(target=updateOrder, args=ids)

t1.start()
t2.start()

【问题讨论】:

  • 您收到错误是因为args 应该是一个参数列表或元组,而您的一开始是空的。您可以通过调用 t2 = threading.Thread(target=updateOrder, args=[ids]) 来消除此错误。
  • 谢谢,有道理!

标签: python multithreading


【解决方案1】:

我认为解决方案是使用 queue

import threading
import queue
from pathlib import Path
from time import sleep

job_file = Path("job_done.txt")

q = queue.Queue()

def updateOrder():
    while True:
        item = q.get()
        sleep(1)
        with open(job_file, 'a') as file_out:
            file_out.write(f"worked on {item}\n")
        q.task_done()


threading.Thread(target=updateOrder, daemon=True).start()

while True:
    try:
        # add job to the queue
        q.put(input("add item : "))
    except KeyboardInterrupt:
        break

q.join()
print('\nAll work completed')

我用sleep 模拟了一个长任务,执行的作业被写入文件而不是通过请求发送,但推理应该是相同的。 适用于 python 3.9.2

【讨论】:

  • 非常感谢,我会试试的!
  • 这似乎在起作用!它并没有像我的代码在修复语法错误后那样创建 100% CPU 负载?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-09
  • 1970-01-01
  • 2019-11-29
  • 2014-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多