Why sometimes the Python subprocess failed to get the correct exit code after the process started?

I am using the Python subprocess to run external scripts in Windows 7. I am trying to get the exit code.


In case 1, I run a python script test1.py.

test1.py

import sys
sys.exit(24)   <--exit code

myscript1.py

import subprocess
process = subprocess.Popen(["python", "C:\\path\\to\\test1.py"], stdout=subprocess.PIPE)
process.wait()
print process.returncode

On the windows command line, when I run the script, I get the following output:

>python test1.py
>
>echo %errorlevel%
>24
>
>python myscript1.py
>24

So you can see that the subprocess can get the correct exit code in this case.


In case 2, I run a batch file test2.cmd.

test2.cmd

EXIT /B 56   <--exit code

myscript2.py

import subprocess
process = subprocess.Popen(["C:\\path\\to\\test2.cmd"], stdout=subprocess.PIPE)
process.wait()
print process.returncode

On the windows command line, when I run the script, I get the following output:

>test2.cmd
>
>echo %errorlevel%
>56
>
>python myscript2.py
>56

So you can see that in this case, the subprocess can also get the correct exit code.


In case 3, I run the SikuliX script.

test3.sikuli

xxx xxx (sikuli script here)
xxx xxx
...
exit(16)   <--exit code

myscript3.py

import subprocess
process = subprocess.Popen(["C:\\path\\to\\runsikuli.cmd", "-r", "C:\\path\\to\\sikuli-script.sikuli"], stdout=subprocess.PIPE)
process.wait()
print process.returncode

On the windows command line, when I run the script, I get the following output:

>C:\path\to\runsikuli.cmd -r C:\path\to\sikuli-script.sikuli
>... (stdout + stderr)
>16
>
>echo %errorlevel%
>16
>
>python myscript3.py
>0

3, script , % errorlevel%. script Python, . 0.

Python 3?

+4
2

, , , Python subprocess (0 ).

, . . Python subprocess ( ) .


, & exit cmd.exe , . " Windows: = True" Python:

from subprocess import check_call

check_call(r'C:\path\to\runsikuli.cmd -r C:\path\to\sikuli-script.sikuli & exit',
           shell=True)
+3

, , Python.

batch.cmd. , :

call %1 -r %2
EXIT /B %errorlevel%

python script:

import subprocess
exitcode = subprocess.call(r'C:\path\to\batch.cmd C:\path\to\runsikuli.cmd C:\path\to\sikuli-script.sikuli', shell=True)
print "Exit Code = "+str(exitcode)
0

Source: https://habr.com/ru/post/1547015/


All Articles