Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to capture subprocess error

In Python, I run an exe made using FORTRAN. I use the subprocess module. that exe accesses and writes to several files. If I make those files readonly, I see the following trace in my Python console.

I tried by using try, except statements. But I could not capture the error. I also tried using p.stdout.readline(). But was unsuccessful.

Is there a systematic way to capture this sort of errors.

Code:

import subprocess
p = subprocess.Popen('C:\\TGSSR\\test.exe' , shell=True, stdout=subprocess.PIPE)

Traceback:

forrtl: severe (9): permission to access file denied, unit 6, file C:\test\mar22_SSOUT\RawReadLog.dat

Image              PC        Routine            Line        Source             
test.exe           0116DC40  Unknown               Unknown  Unknown
test.exe           0113D42F  Unknown               Unknown  Unknown
test.exe           0112AE97  Unknown               Unknown  Unknown
test.exe           0112A1DA  Unknown               Unknown  Unknown
test.exe           0110D746  Unknown               Unknown  Unknown
test.exe           0108B9AC  Unknown               Unknown  Unknown
test.exe           01173FE3  Unknown               Unknown  Unknown
test.exe           011588F5  Unknown               Unknown  Unknown
kernel32.dll       76D33677  Unknown               Unknown  Unknown
ntdll.dll          77A39F42  Unknown               Unknown  Unknown
ntdll.dll          77A39F15  Unknown               Unknown  Unknown
like image 757
py_works Avatar asked Dec 26 '22 11:12

py_works


1 Answers

Run the process:

p = subprocess.Popen(['C:\\TGSSR\\test.exe'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# shell = True is not needed

To capture the error message:

stdout, stderr = p.communicate()
# stdout = normal output
# stderr = error output

Check the process return code:

if p.returncode != 0:
    # handle error
like image 172
kirbyfan64sos Avatar answered Jan 05 '23 15:01

kirbyfan64sos