2005年02月04日 星期五 09:25
好像os.path.expanduser并不会抛出异常,仅仅是做字符串替换,可以省一点代码:
def getHomeDir():
path1 = os.path.expanduser('~')
path2 = os.environ.get('HOME')
path3 = os.environ.get('USERPROFILE')
if not os.path.exists(path1):
if not os.path.exists(path2):
if not os.path.exists(path3):
return os.getcwd()
else: return path3
else: return path2
else: return path1
另外,path1 = os.path.expanduser('~')是否已包含了os.environ.get('HOME')
的功能?
Wang Kebo 写道:
> 以下的代码是从limodou的blog上截下来的。不过,总觉得这段代码不是太优雅,
> 谁可以想到更加pythonic的实现方式?我觉得这样的讨论,能使我们更加熟悉
> python的特性。
> 如果谁有精力,可以建立一个Python Quiz,类似于Ruby Quiz
> http://www.rubyquiz.com/
> 或Perl Quiz,
> http://perl.plover.com/qotw/
> 每星期出个小题目大家来讨论,看看怎样才是最优雅的实现方式。
>
>     def getHomeDir():
>     ''' Try to find user's home directory, otherwise return current
>     directory.'''
>     try:
>     path1=os.path.expanduser("~")
>     except:
>     path1=""
>     try:
>     path2=os.environ["HOME"]
>     except:
>     path2=""
>     try:
>     path3=os.environ["USERPROFILE"]
>     except:
>     path3=""
>
>     if not os.path.exists(path1):
>     if not os.path.exists(path2):
>     if not os.path.exists(path3):
>     return os.getcwd()
>     else: return path3
>     else: return path2
>     else: return path1
>
> __
> Best Regards,
> Wang Kebo
>
> HomePage: http://www.huihoo.org/~mep <http://www.huihoo.org/%7Emep>
> Blog: http://sharing.blogbus.com <http://sharing.blogbus.com/>
>
>------------------------------------------------------------------------
>
>_______________________________________________
>python-chinese list
>python-chinese at lists.python.cn
>http://python.cn/mailman/listinfo/python-chinese
>  
>
Zeuux © 2025
京ICP备05028076号