如何在Python / Django中调试子进程调用

时间:2017-03-24 20:15:49

标签: python centos

在我的Python / Django代码中,我调用gdalbuildvrt进程。此过程应创建.VRT文件,但它不会。为了检查它,我将子进程输出写入调试文件。我就是这样做的:

process = subprocess.Popen(["gdalbuildvrt", mosaic, folder], stdout=subprocess.PIPE)
stdout = process.communicate()[0]

with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "debug.txt"), 'w') as file:
    file.write('{}'.format(stdout) + " -> " + mosaic)

结果我在debug.txt文件中看到了这个:

b'0...10...20...30...40...50...60...70...80...90...100 - done.\n' -> /var/www/vwrapper/accent/accent/layers/raw/mosaic.vrt

因此,正如您可以看到调试语句的第一部分所说的那样:

0...10...20...30...40...50...60...70...80...90...100 - done.

第二部分说,应该创建/var/www/vwrapper/accent/accent/layers/raw/mosaic.vrt。但是,当我转到目标文件夹并刷新它时,我看不到mosaic.vrt文件。那么,这可能有什么问题,我该如何解决呢?我应该在Windows机器上添加它100%正常,但在CentOS上它没有。

1 个答案:

答案 0 :(得分:2)

process = subprocess.Popen(["gdalbuildvrt", mosaic, folder], 
                           stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
ret = process.returncode

process = subprocess.Popen(["gdalbuildvrt", mosaic, folder], 
                           stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

会将stderr重定向到stdout

然后记录这两件事:

所有错误记录都应该在stderr上,而不是stdout。任何返回代码都会通过process.returncode显示。

您也可以使用其中一个较高的流程,例如subprocess.check_call()