首先,删除异常块,因为它隐藏了错误的详细信息,反正Popen等subprocess方法仅抛出异常时,他们无法启动(没有发现因为命令)命令,这意味着mount实际上是调用。
其次,你真的不需要Popen,但call(和作为奖金,你直接将返回代码)
rc = subprocess.call(["mount","-t","cifs", "-o",
"username="+username+",password="+password,
"//"+hostname+"/c$",
"/mntDir/"+mountDir])
if rc:
print("mount failed")
在你的情况下,问题是一般异常块。
这种方法:
def makeDir():
tempDir = random.randrange(111111,999999)
subprocess.Popen(["mkdir","/mntDir/"+str(tempDir)])
return tempDir
返回一个整数,因此,如果您删除异常块,因为你要添加一个字符串一个整数(TypeError: Can't convert 'int' object to str implicitly),你会得到错误。这是一个简单的错误,你可以看到它是否不适合愚蠢的例外情况,误导你。
但与通用的try/except块没有任何参数,你只是得到mount failed无用的消息。 从来没有保护你的陈述与try:/except:,这是适得其反。
如果你真的想这样做,这样做:
try:
some_command
except Exception as e:
# print detailed exception, not just "error"
print("Something went wrong "+str(e))
现在总结一下,这里是你的代码的固定版本(稍作改进作为奖金):
import subprocess,os
import random
def makeDir():
# directly create directory name as a string
tempDir = "/mntDir/{}".format(random.randrange(111111,999999))
# no need for a subprocess, python handles this well!
os.mkdir(tempDir)
# returns the absolute directory name, as string
return tempDir
def mountShare(hostname, username, password):
mountDir = makeDir()
rc = subprocess.call(["mount","-t","cifs", "-o",
"username="+username+",password="+password,
"//"+hostname+"/c$",
mountDir])
if rc!=0:
print("Mounting failed")