我编写了一个小型 Django 应用程序,它根据用户输入执行交互式程序并将输出作为结果返回。但由于某种原因,子进程挂起。在验证日志时,我发现必须给出“\n”作为对挑战的响应的地方,该响应似乎从未做出过。有趣的是,如果我从 Django 外部运行相同的代码,即从 python 模块或交互式 shell 运行相同的代码,子进程可以顺利运行。我假设 Django 使用的环境中的某些设置是罪魁祸首。以下是我编写的代码片段:
def runtests(test_name, selective=False, tests_file=''):
if selective:
run_cmd = ['runtest', '--runfromfile', tests_file, test_name]
else:
run_cmd = 'runtest %s' % (test_name)
print 'Executing command .. '
print run_cmd
p = subprocess.Popen(run_cmd, shell=False, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
return p.stdout.read()
def result(request):
test_name = request.GET['test_name']
if not test_name:
return render_to_response('webrun/execute.html', {'error_flag':True})
in_file = os.path.abspath('webrun/log/%s_in.xml' % test_name)
suites = dict([(field[len('suite_'):],value)
for field,value in request.GET.items()
if field.startswith('suite_')])
if suites:
_from_dict_to_xml(suites, in_file, test_name)
output = runtests(test_name, bool(suites), in_file)
return render_to_response('webrun/result.html', {'output':output})
我尝试用旧的 os.system 方法替换 subprocess 。但即便如此,它也挂在完全相同的地方。同样,如果我从 Django 执行相同的代码,这也会运行。