如何在Python中获取PATH环境变量分隔符?

问题:如何在Python中获取PATH环境变量分隔符?

当需要将多个目录串联在一起时(例如在可执行文件搜索路径中),存在一个与OS相关的分隔符。对于Windows ';',对于Linux':'。Python中有没有一种方法可以分割哪个字符?

在对此问题的讨论中,如何使用python找出我的python路径?,建议这样os.sep做。这个答案是错误的,因为它是目录或文件名组成部分的分隔符,等于'\\''/'

When multiple directories need to be concatenated, as in an executable search path, there is an os-dependent separator character. For Windows it’s ';', for Linux it’s ':'. Is there a way in Python to get which character to split on?

In the discussions to this question How do I find out my python path using python? , it is suggested that os.sep will do it. That answer is wrong, since it is the separator for components of a directory or filename and equates to '\\' or '/'.


回答 0


回答 1

它是os.pathsep

It is os.pathsep


回答 2

使它更加明确(对于像我这样的python新手)

import os
print(os.pathsep)

Making it a little more explicit (For python newbies like me)

import os
print(os.pathsep)

回答 3

好,所以有:

  • os.pathsep这是;并且是PATH环境变量中的分隔符;
  • os.path.sep/在Unix / Linux和\Windows中,这是路径成分之间的隔板。

相似性是造成混乱的根源。

OK, so there are:

  • os.pathsep that is ; and which is a separator in the PATH environment variable;
  • os.path.sep that is / in Unix/Linux and \ in Windows, which is a separator between path components.

The similarity is a source of confusion.


回答 4

这是您的工作目录/特定文件夹的示例路径-

 import os
 my = os.path.sep+ "testImages" + os.path.sep + "imageHidden.png"
 print(my)

Linux-的输出

/home/*******/Desktop/folder/PlayWithPy/src/testImages/imageHidden.png

Windows输出

C:\\Users\\Administrator\\Desktop\\folder\\tests\\testImages\\imageHidden.png

This is a sample path for your working directory/specific folder –

 import os
 my = os.path.sep+ "testImages" + os.path.sep + "imageHidden.png"
 print(my)

Output for Linux-

/home/*******/Desktop/folder/PlayWithPy/src/testImages/imageHidden.png

Output for Windows-

C:\\Users\\Administrator\\Desktop\\folder\\tests\\testImages\\imageHidden.png