Python 2.4 subces.CalledProcessError替换
我正在尝试向我的子流程添加Python 2.4 subces.CalledProcessError替换,python,python-2.4,python-2.3,Python,Python 2.4,Python 2.3,我正在尝试向我的子流程添加try/except try: mountCmd = 'mount /dev/%s %s%s' % (splitDevice, homeDir, splitDevice) dev = '/dev/%s' % splitDevice subprocess.check_call(mountCmd, shell=True) except subprocess.CalledP
try/except
try:
mountCmd = 'mount /dev/%s %s%s' % (splitDevice, homeDir, splitDevice)
dev = '/dev/%s' % splitDevice
subprocess.check_call(mountCmd, shell=True)
except subprocess.CalledProcessError:
continue
上面的snipet可以工作,但是如果主机在低于2.5的Python版本上执行代码,那么代码将失败,因为Python版本2.5中引入了CalledProcessError
有人知道我可以用什么替代品来代替调用的过程错误
模块吗
编辑:
这就是我解决问题的方法
mountCmd = 'mount /dev/%s %s%s' % (splitDevice, homeDir, splitDevice)
dev = '/dev/%s' % splitDevice
returnCode = 0
#CalledProcessError module was introduced in version 2.5 of python. If older version do the following.
if sys.hexversion < 0x02050000:
try:
p3 = subprocess.Popen(mountCmd, shell=True, stdout=subprocess.PIPE)
output = p3.communicate()[0]
returnCode = p3.returncode
except:
pass
if returnCode != 0:
continue
else: #If version of python is newer than 2.5 use CalledProcessError.
try:
subprocess.check_call(mountCmd, shell=True)
except subprocess.CalledProcessError, e:
continue
mountCmd='mount/dev/%s%s%s'(splitDevice、homeDir、splitDevice)
dev='/dev/%s'%1!''拆分设备
returnCode=0
#python版本2.5中引入了CalledProcessError模块。如果是旧版本,请执行以下操作。
如果sys.hexversion<0x02050000:
尝试:
p3=subprocess.Popen(mountCmd,shell=True,stdout=subprocess.PIPE)
输出=p3.communicate()[0]
returnCode=p3.returnCode
除:
通过
如果返回代码!=0:
持续
else:#如果python版本高于2.5,请使用CalledProcessError。
尝试:
子进程检查调用(mountCmd,shell=True)
除了subprocess.CalledProcessError之外,e:
持续
异常子进程。被调用的进程错误
Exception raised when a process run by check_call() or check_output() returns a non-zero exit status.
returncode
Exit status of the child process.
cmd
Command that was used to spawn the child process.
output
Output of the child process if this exception is raised by check_output(). Otherwise, None.
。这意味着您需要检查check_all或check_output运行的进程是否具有非零输出。是否应该使用Popen then而不是check_call()?以下是与check_call相关的内容:“注意,不要将stdout=PIPE或stderr=PIPE与此函数一起使用,因为这可能会根据子进程输出卷发生死锁。当您需要管道时,使用Popen和communicate()方法。任何能够让您获得过程结果的策略都或多或少地解决了问题,但如果我是您,我只会将此代码应用于旧Python。新的Python应该使用所有有趣的功能。问题是我不知道Python的哪个版本将被使用,但我同意我可能会添加一些东西,首先检查Python版本是否为2.5或更高版本,然后选择使用什么。谢谢,当我有机会测试这个时,我会更新我的帖子。你可以确定正在使用的版本。查看此帖子:感谢@lajos的帮助,我也实现了版本检查。