问题
This piece of script in python:
cmd = 'installer.exe --install ...' #this works fine, the ... just represent many arguments
process = subprocess.Popen(cmd)
process.wait()
print(process.returncode)
This code works fine in my opinion, the problem is the value of .returncode
.
The installer.exe is ok, did many test to this, and now i trying to create a script in python to automate a test for many days executing this installer.exe .
The installer.exe return: - Success is 0; - Failure and errors are NEGATIVE numbers
I have a specific error that is -307 that installer.exe return. But python when execute print(process.returncode)
its shows 4294966989 ... How can i deal with negative numbers in python, to show in this case the -307?
I am new to python and the env is win7 32 and python 3.4.
EDIT: the final code working The porpose of this code is to run many simple test:
import subprocess, ctypes, datetime, time
nIndex = 0
while 1==1:
cmd = 'installer.exe --reinstall -n "THING NAME"'
process = subprocess.Popen( cmd, stdout=subprocess.PIPE )
now = datetime.datetime.now()
ret = ctypes.c_int32( process.wait() ).value
nIndex = nIndex + 1
output = str( now ) + ' - ' + str( nIndex ) + ' - ' + 'Ret: ' + str( ret ) + '\n'
f = open( 'test_result.txt', 'a+' )
f.write( output )
f.closed
print( output )
回答1:
Using NumPy: view the unsigned 32-bit int, 4294966989, as a signed 32-bit int:
In [39]: np.uint32(4294966989).view('int32')
Out[39]: -307
回答2:
Using only the standard library:
>>> import struct
>>> struct.unpack('i', struct.pack('I', 4294966989))
(-307,)
回答3:
To convert positive 32-bit integer to its two's complement negative value:
>>> 4294966989 - (1 << 32) # mod 2**32
-307
As @Harry Johnston said, Windows API functions such as GetExitCodeProcess()
use unsigned 32-bit integers e.g., DWORD
, UINT
. But errorlevel
in cmd.exe
is 32-bit signed integer and therefore some exit codes (> 0x80000000) may be shown as negative numbers.
来源:https://stackoverflow.com/questions/27842166/how-to-deal-with-negative-numbers-that-returncode-get-from-subprocess-in-python