2005年02月04日 星期五 09:42
Wang Kebo wrote:
> 以下的代码是从limodou的blog上截下来的。不过,总觉得这段代码不是太优雅,
> 谁可以想到更加pythonic的实现方式?我觉得这样的讨论,能使我们更加熟悉
> python的特性。
[snip]
> 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=""
os.path.expanduser("~") 应该和 os.environ["HOME"]是等价的。
> 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
可以简化成:
def getHomeDir():
path1 = os.environ.get('HOME', '')
path2 = os.environ.get('USERPROFILE', '')
return os.path.exists(path1) and path1 \
or os.path.exists(path2) and path2 \
or os.getcwd()
2005年02月04日 星期五 10:36
是要简洁得多。
不过从我多次测试来看,这样的写法好像速度会慢一些。
Qiangning Hong 写道:
>Wang Kebo wrote:
>
>
>>以下的代码是从limodou的blog上截下来的。不过,总觉得这段代码不是太优雅,
>>谁可以想到更加pythonic的实现方式?我觉得这样的讨论,能使我们更加熟悉
>>python的特性。
>>
>>
>
>[snip]
>
>
>
>> 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=""
>>
>>
>
>os.path.expanduser("~") 应该和 os.environ["HOME"]是等价的。
>
>
>
>> 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
>>
>>
>
>可以简化成:
>
>def getHomeDir():
> path1 = os.environ.get('HOME', '')
> path2 = os.environ.get('USERPROFILE', '')
> return os.path.exists(path1) and path1 \
> or os.path.exists(path2) and path2 \
> or os.getcwd()
>_______________________________________________
>python-chinese list
>python-chinese at lists.python.cn
>http://python.cn/mailman/listinfo/python-chinese
>
>
>
>
Zeuux © 2025
京ICP备05028076号