在subprocess.check_call方法中传递stdout kwarg在python 3中返回Apache / mod_wsgi错误

时间:2018-12-04 15:55:14

标签: python django unit-testing subprocess

在Django中进行单元测试时,我正在将stdout重定向到一个文件,以便不在屏幕上显示输出。

我正在将sys.stdout保存在变量中,并让if调用subprocess.check_call

# if testing or running jenkins, redirects stdout to a temp file
if 'test' in sys.argv or 'jenkins' in sys.argv or 'runserver' in sys.argv:
    outfile = tempfile.NamedTemporaryFile(suffix='.txt')
else:
    outfile = sys.stdout
try:
    subprocess.check_call(cmd, stdout=outfile)
except subprocess.CalledProcessError:
    messages.error(request, DOWNLOAD_ERROR_MESSAGE)
    return HttpResponseRedirect(
        reverse('experiment-detail', kwargs={'slug': experiment.slug})
    )

在使用Django runserver manage.py命令在本地主机上运行时,先创建outfile = sys.stdout,然后subprocess.check_call(cmd, stdout= outfile)在屏幕上正确显示stdout输出,但是以某种方式在Django在Apache / mod_wsgi上运行时,Apache拒绝接受sys.outfile作为stdout参数的值。

出现的错误是:

Internal Server Error: /downloads/163/
Traceback (most recent call last):
  File "/var/lib/nep-system/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/var/lib/nep-system/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _getresponse
    response = self.process_exception_by_middleware(e, request)
  File "/var/lib/nep-system/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _geresponse
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/var/lib/nep-system/portal/downloads/views.py", line 180, in download_view
    compressed_file = remove_files(compressed_file, request, experiment)
  File "/var/lib/nep-system/portal/downloads/views.py", line 155, in remove_files
    subprocess.check_call(cmd, stdout=sys.stdout)
  File "/usr/lib/python3.5/subprocess.py", line 266, in check_call
    retcode = call(*popenargs, **kwargs)
  File "/usr/lib/python3.5/subprocess.py", line 247, in call
    with Popen(*popenargs, **kwargs) as p:
  File "/usr/lib/python3.5/subprocess.py", line 640, in __init__
    errread, errwrite) = self._get_handles(stdin, stdout, stderr)
  File "/usr/lib/python3.5/subprocess.py", line 1135, in _get_handles
    c2pwrite = stdout.fileno()
OSError: Apache/mod_wsgi log object is not associated with a file descriptor.

任何人都可以澄清这里发生了什么吗?

0 个答案:

没有答案