如何使用子进程实时获取运行命令的输出?

时间:2018-11-14 16:01:33

标签: python python-3.x subprocess

我有一个烧瓶路由,该路由使用子进程模块来调用服务器上的Python脚本。我的问题是此脚本下载文件,并且无法确定执行该文件所花费的时间。我想通过获取子流程的输出以某种方式更新客户端。这是整个路线:

@app.route("/adyen_request_download", methods=["POST", "GET"])
def adyen_request_download():
    merchant_manager = MerchantManager()
    error = None
    if request.method == "POST":
        pfjs = []
        prefixes = []
        extensions = []
        ftpd = "/var/ftp/CONTROLE_TESTE"
        for result in request.get_json():
            if result["name"] == "pfj-select":
                pfjs.append(result["value"])
            if result["name"] == "prefix-select":
                prefixes.append(result["value"])
            if result["name"] == "extension-select":
                extensions.append(result["value"])
            if result["name"] == "start-date":
                start_date = result["value"]

        logging.info(f"Requisição de download manual de arquivos realizada.")
        logging.info(f">> PFJs: {str(pfjs)}")
        logging.info(f">> Prefixos: {str(prefixes)}")
        logging.info(f">> Extensões: {str(extensions)}")
        logging.info(f">> Data: {start_date}")
        if prefixes and not extensions:
            run_command = f'python ../InputDataController/acquirer_file_downloader.py --acquirer "adyen" --pfj {" ".join(pfjs)} --prefix {" ".join(prefixes)} --date "{start_date}" --ftpd "{ftpd}" --force'
        elif extensions and not prefixes:
            run_command = f'python ../InputDataController/acquirer_file_downloader.py --acquirer "adyen" --pfj {" ".join(pfjs)} --ext {" ".join(extensions)} --date "{start_date}" --ftpd "{ftpd}" --force'
        elif not prefixes and not extensions:
            run_command = f'python ../InputDataController/acquirer_file_downloader.py --acquirer "adyen" --pfj {" ".join(pfjs)} --date "{start_date}" --ftpd "{ftpd}" --force'
        elif prefixes and extensions:
            run_command = f'python ../InputDataController/acquirer_file_downloader.py --acquirer "adyen" --pfj {" ".join(pfjs)} --prefix {" ".join(prefixes)} --ext {" ".join(extensions)} --date "{start_date}" --ftpd "{ftpd}" --force'
        subprocess.run(run_command, shell=True) # HERE <<<<<<<
    return json.dumps({"result": "ok"})

我看到了getoutput方法,但这并不是我想要的,我需要在某些文件中以实时的形式获取shell输出。有可能吗?

1 个答案:

答案 0 :(得分:2)

根据documentation,subprocess.run有一个stdout参数。因此,我想如果您将文件处理程序传递给它,输出将实时写入并且您应该能够读取它。

类似的东西(未经测试):

with open(yourfile, "r+") as output_file:
    subprocess.run(run_command, shell=True, stdout=output_file)
    // loop to read the file while subprocess running