簡體   English   中英

從 python 腳本運行多個終端並執行命令 (Ubuntu)

[英]Run multiple terminals from python script and execute commands (Ubuntu)

我擁有的是一個文本文件,其中包含需要從在線應用程序中刪除的所有項目。 每個需要刪除的項目都必須一次發送 1 個。 為了加快刪除過程,我將文本文件中的項目划分為多個文本文件,並在多個終端中運行腳本(刪除時間約為 130,對於 ~7000 項,刪除時間不到 30 分鍾)。

這是刪除腳本的代碼:

from fileinput import filename
from WitApiClient import WitApiClient
import os


dirname = os.path.dirname(__file__)
parent_dirname = os.path.dirname(dirname)
token = input("Enter the token")
file_name = os.path.join(parent_dirname, 'data/deletion_pair.txt')

with open(file_name, encoding="utf-8") as file:
        templates = [line.strip() for line in file.readlines()]

for template in templates:
    entity, keyword = template.split(", ")
    print(entity, keyword)
    resp = WitApiClient(token).delete_keyword(entity, keyword)
    print(resp)

因此,我將 deletion_pair.txt 中的項目分開,並在新終端(~130 個終端)中多次運行此腳本。 有沒有辦法使這個過程自動化或以更有效的方式進行?

我使用線程同時運行多個函數:

from fileinput import filename
from WitApiClient import WitApiClient
import os
from threading import Thread

dirname = os.path.dirname(__file__)
parent_dirname = os.path.dirname(dirname)
token = input("Enter the token")
file_name = os.path.join(parent_dirname, 'data/deletion_pair.txt')

with open(file_name, encoding="utf-8") as file:
    templates = [line.strip() for line in file.readlines()]

batch_size = 20
chunks = [templates[i: i + batch_size] for i in range(0, len(templates), batch_size)]

def delete_function(templates, token):
    for template in templates:
        entity, keyword = template.split(", ")
        print(entity, keyword)
        resp = WitApiClient(token).delete_keyword(entity, keyword)
        print(resp)

for chunk in chunks:
    thread = Thread(target=delete_function, args=(chunk, token))
    thread.start()

它奏效了,任何人都有任何其他解決方案。 請發帖,或者如果可以更有效地編寫相同的代碼,請告知。 謝謝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM