带有django命令的双引号和空格的Python子进程

时间:2019-03-20 11:22:43

标签: python django subprocess

我正在使用此node plugin运行django管理命令。

如果我直接执行命令,它将起作用:

sls wsgi manage local -c "check --list-tags"

如果我调用一个将其作为子进程调用的python脚本,它将找不到命令:

import subprocess
proc = subprocess.Popen(['sls', 'wsgi', 'manage', 'local', '-c', '"check --list-tags"'])
(out, err) = proc.communicate()


"Traceback (most recent call last):\n  File \"/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py\", line 102, in call_command\n    app_name = get_commands()[command_name]\nKeyError: 'check --list-tags'\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n  File \"./wsgi_handl
    er.py\", line 89, in handler\n    management.call_command(*shlex.split(meta.get(\"data\", \"\")))\n  File \"/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py\", line 104, in call_command\n    raise CommandError(\"Unknown command: %r\" % command_name)\ndjango.core.management.base.CommandError: Unknown command: 'check --list-tags'\n
    "

如果我执行的命令不包含任何空格,则该命令可以正常工作,例如:

subprocess.Popen(['sls', 'wsgi', 'manage', 'local', '-c', '"makemigrations"'])

1 个答案:

答案 0 :(得分:0)

如果您使用shell = True,则可以将完整的命令作为字符串传递,尝试然后在以后进行优化

proc = subprocess.Popen('sls wsgi manage local -c "check --list-tags"' shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)