2015-01-08 56 views
1

这一段脚本在python:如何处理从Python中的子进程返回的负数?

cmd = 'installer.exe --install ...' #this works fine, the ... just represent many arguments 
process = subprocess.Popen(cmd) 
process.wait() 
print(process.returncode) 

此代码的工作在我看来不错,问题是.returncode值。

installer.exe没问题,对此做过很多测试,现在我试图在python中创建一个脚本来自动执行测试,执行installer.exe多日。

installer.exe返回: - 成功为0; - 失败和错误是负数

我有一个特定的错误是-307 installer.exe返回。但是,执行时的python print(process.returncode)它的显示4294966989 ...我如何处理python中的负数,在这种情况下显示-307?

我是python的新手,env是win7 32和python 3.4。

编辑:最终代码工作 此代码的porpose是运行许多简单的测试:

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) 
+3

请注意,Windows退出代码被定义为32位*无符号*整数,所以Python实际上在这里做了正确的事情。 –

+1

无关:使用'returncode = subprocess.call(cmd)'而不是'Popen(cmd).wait()'。除非从管道读取数据,否则不要使用'stdout = PIPE'。如果要放弃输出,请使用'stdout = subprocess.DEVNULL'。打印('{now} - {nIndex} - Ret:{ret}'格式,而不是多个'str()'调用, (** vars()),file = file)' – jfs

+0

不要把解决方案放到问题中。将其作为回答代替 – jfs

回答

3

使用NumPy的:查看无符号的32位int,4294966989,作为有符号的32位位INT:

In [39]: np.uint32(4294966989).view('int32') 
Out[39]: -307 
+1

或纯c语言中的'ctypes.c_int32(4294966989).value'。 –

+1

对于这种情况,我喜欢@AshwiniChaudhary用ctypes显示的方式......不需要额外的包装和输出是干净的...... –

+0

但是......谢谢大家,问题解决了......并且我学到了更多: ) –

5

只使用标准库:

>>> import struct 
>>> struct.unpack('i', struct.pack('I', 4294966989)) 
(-307,) 
1

至正32位整数转换成其two's complement negative value

>>> 4294966989 - (1 << 32) # mod 2**32 
-307 

@Harry Johnston said如,Windows API函数如GetExitCodeProcess()使用无符号的32位整数例如,DWORDUINT。但errorlevelcmd.exe是32位签名整数,因此一些退出代码(> 0x80000000)可能会显示为负数。

相关问题