我需要尝试,除了帮助或任何其他最好的方式来存档我的要求。请帮忙
const char *x ="abc";
const char *y ="defgh";
提供以下输出:
mount_status = check_output (["mount", "/dev/sr{}".format(x), "/mnt"])
如果我得到选项1,那么它应该继续
如果我获得选项2,那么它应该终止程序。
我尝试的是在下面的脚本中,它无法正常工作
1. If medium does not found then below messages appears and stops the program.
mount: no medium found on /dev/srX
Traceback (most recent call last):
File "test.py", line 39, in <module>
software_foundation()
File "test.py", line 31, in software_foundation
mount_status = check_output (["mount", "/dev/sr{}".format(x), "/mnt"])
File "/usr/lib64/python2.7/subprocess.py", line 573, in check_output
raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '['mount', '/dev/srX', '/mnt']' returned non-zero exit status 32
2. If medium exits but it already mounted then below messages appears and stops the program.
mount: /dev/srX is write-protected, mounting read-only
mount: /dev/srX is already mounted or /mnt busy
/dev/srX is already mounted on /mnt
Traceback (most recent call last):
File "test1.py", line 39, in <module>
software_foundation()
File "test1.py", line 31, in software_foundation
mount_status = check_output (["mount", "/dev/sr{}".format(x), "/mnt"])
File "/usr/lib64/python2.7/subprocess.py", line 573, in check_output
raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '['mount', '/dev/srX', '/mnt']' returned non-zero exit status 32
答案 0 :(得分:0)
我从你的问题中收集到你不知道怎么写try...except
。
将try
放在引发要捕获的异常的行之前。将except
放在if
之前 - 测试如何处理异常。
import subprocess
import sys
for x in range(0,5):
try:
mount_status = subprocess.check_output (["mount", "/dev/sr{}".format(x), "/mnt"])
except subprocess.CalledProcessError as details:
if "is write-protected, mounting read-only" in details:
break
elif "is already mounted on /mnt" in details:
print "/mnt has already mounted. Unmount /mnt and rerun the script"
sys.exit()
检查mount_status
- 测试中的if
无效,因为如果您对check_output()
的调用成功,则只会获得一个值。如果命令的返回码非零,则check_output()
会引发异常,因此mount_status
的赋值永远不会发生。