1

I want my Project, built in PYTHON to support Windows Linux MAC in any terminal(MAC, CYGWIN, Windows etc). I can able to achieve but I am facing some issue When I run the following

import os
mypath = os.path.join('users','scripts', 'pythonsample')
print mypath

In windows command prompt output is

users\scripts\pythonsample

In MAC terminal output is

users/scripts/pythonsample

Also, when I run the following code

import glob
glob.glob(os.path.join('users','scripts', 'pythonsample','*.*'))

In windows command prompt output is

[users/scripts\\pythonsample\\a1.py,
users/scripts\\pythonsample\\a2.py,
users/scripts\\pythonsample\\a3.py
users/scripts\\pythonsample\\a4.py]

In MAC terminal output is

[users/scripts/pythonsample/a1.py,
users/scripts/pythonsample/a2.py,
users/scripts/pythonsample/a3.py
users/scripts/pythonsample/a4.py]

So to parse and get get the name of the file without whole path becomes difficult in multiple platforms.

I can write a if else block to decide whether the script is running in Windows or MAC or CGYWIN.

import sys
#Output of below command is Win32, linux2, darwin, cgywin 
print(sys.platform)

but is there a easy way to accomplish this with out if else block?

4

1 回答 1

5

这正是您应该期待的。在 Windows 上,os.path为您提供 Windows 样式的路径;在 Mac OS X 上,它为您提供 POSIX 样式的路径。

如果您希望保证 POSIX 路径的所有内容,请不要使用os.pathposixpath而是使用。

另一方面,如果您的路径即使在 Windows 上也可能是 POSIX 格式(因为 Windows 的大多数部分都处理 POSIX 样式的路径,并且许多工具会生成 POSIX 样式的路径)并且想要保证您有本机路径,调用os.path.normpath.

于 2013-08-09T00:58:38.053 回答