Django从子进程中获得干净的回报。

时间:2019-02-09 21:39:46

标签: python django shell subprocess

我有一个调用子进程的celery任务。又名Shell cmd,但由于某些原因,cmd的输出未保存到用户字段中,而是进程内存ID!?!?

[2019-02-09 21:35:05,526: INFO/MainProcess] Received task: MyProject.tasks.allocate_new_btc_address[08d7db34-5710-4224-be07-c968599d9039]  
[2019-02-09 21:35:05,540: WARNING/ForkPoolWorker-9] <subprocess.Popen object at 0x7f31063d79b0>
[2019-02-09 21:35:05,540: INFO/ForkPoolWorker-9] MyProject.tasks.allocate_new_btc_address[08d7db34-5710-4224-be07-c968599d9039]: New BTC address has been allocated to a user account
[2019-02-09 21:35:05,540: INFO/ForkPoolWorker-9] Task MyProject.tasks.allocate_new_btc_address[08d7db34-5710-4224-be07-c968599d9039] succeeded in 0.012948354000400286s: None
iubcasiuiuBIUcb723iub7c8732iewe

tasks.py

@app.task
def allocate_new_btc_address(user_pk):
    user = User.objects.get(pk=user_pk)
    new_address = subprocess.Popen(['electrum', 'createnewaddress'])
    try:
        user.acc_btc_addr = new_address
        user.save()
        print(new_address)
        logger.info("New BTC address has been allocated to a user account")
    except Exception as e:
        print(e)

多数民众赞成在保存到字段的值:

<subprocess.Popen object at 0x7f31063d79b0>

预先感谢

1 个答案:

答案 0 :(得分:1)

Popen返回一个对象。要直接获取输出,请使用subprocess.check_output()函数:

from subprocess import check_output
new_address = check_output(['electrum', 'createnewaddress'])