标签归档:cross-platform

在Python中获取临时目录的跨平台方法

问题:在Python中获取临时目录的跨平台方法

是否有跨平台的途径来获取 temp Python 2.6中目录?

例如,在Linux /tmp下为XP,而在XP下为C:\Documents and settings\[user]\Application settings\Temp

Is there a cross-platform way of getting the path to the temp directory in Python 2.6?

For example, under Linux that would be /tmp, while under XP C:\Documents and settings\[user]\Application settings\Temp.


回答 0

那将是tempfile模块。

它具有获取临时目录的功能,还具有一些在其中创建命名或未命名临时文件和目录的快捷方式。

例:

import tempfile

print tempfile.gettempdir() # prints the current temporary directory

f = tempfile.TemporaryFile()
f.write('something on temporaryfile')
f.seek(0) # return to beginning of file
print f.read() # reads data back from the file
f.close() # temporary file is automatically deleted here

为了完整起见,以下是根据文档搜索临时目录的方式:

  1. TMPDIR环境变量命名的目录。
  2. TEMP环境变量命名的目录。
  3. TMP环境变量命名的目录。
  4. 特定于平台的位置:
    • RiscOS上,由Wimp$ScrapDir环境变量。
    • 的Windows,目录C:\TEMPC:\TMP\TEMP,并\TMP按此顺序。
    • 在所有其他平台,目录/tmp/var/tmp以及/usr/tmp在这个顺序。
  5. 不得已时使用当前工作目录。

That would be the tempfile module.

It has functions to get the temporary directory, and also has some shortcuts to create temporary files and directories in it, either named or unnamed.

Example:

import tempfile

print tempfile.gettempdir() # prints the current temporary directory

f = tempfile.TemporaryFile()
f.write('something on temporaryfile')
f.seek(0) # return to beginning of file
print f.read() # reads data back from the file
f.close() # temporary file is automatically deleted here

For completeness, here’s how it searches for the temporary directory, according to the documentation:

  1. The directory named by the TMPDIR environment variable.
  2. The directory named by the TEMP environment variable.
  3. The directory named by the TMP environment variable.
  4. A platform-specific location:
    • On RiscOS, the directory named by the Wimp$ScrapDir environment variable.
    • On Windows, the directories C:\TEMP, C:\TMP, \TEMP, and \TMP, in that order.
    • On all other platforms, the directories /tmp, /var/tmp, and /usr/tmp, in that order.
  5. As a last resort, the current working directory.

回答 1

这应该做您想要的:

print tempfile.gettempdir()

对于我的Windows机器,我得到:

c:\temp

在我的Linux机器上,我得到:

/tmp

This should do what you want:

print tempfile.gettempdir()

For me on my Windows box, I get:

c:\temp

and on my Linux box I get:

/tmp

回答 2

我用:

from pathlib import Path
import platform
import tempfile

tempdir = Path("/tmp" if platform.system() == "Darwin" else tempfile.gettempdir())

这是因为在MacOS,即达尔文,tempfile.gettempdir()os.getenv('TMPDIR')返回一个值,如'/var/folders/nj/269977hs0_96bttwj2gs_jhhp48z54/T'; 这是我并不总是想要的。

I use:

from pathlib import Path
import platform
import tempfile

tempdir = Path("/tmp" if platform.system() == "Darwin" else tempfile.gettempdir())

This is because on MacOS, i.e. Darwin, tempfile.gettempdir() and os.getenv('TMPDIR') return a value such as '/var/folders/nj/269977hs0_96bttwj2gs_jhhp48z54/T'; it is one that I do not always want.


回答 3

最简单的方法,基于@nosklo的注释和 答案

import tempfile
tmp = tempfile.mkdtemp()

但是,如果要手动控制目录的创建,请执行以下操作:

import os
from tempfile import gettempdir
tmp = os.path.join(gettempdir(), '.{}'.format(hash(os.times())))
os.makedirs(tmp)

这样,您就可以在完成以下操作后轻松清理自己(出于隐私,资源,安全性等方面的考虑):

from shutil import rmtree
rmtree(tmp, ignore_errors=True)

这类似于Google Chrome和Linux systemd这样的应用程序。他们只是使用较短的十六进制哈希值和特定于应用的前缀来“宣传”它们的存在。

The simplest way, based on @nosklo’s comment and answer:

import tempfile
tmp = tempfile.mkdtemp()

But if you want to manually control the creation of the directories:

import os
from tempfile import gettempdir
tmp = os.path.join(gettempdir(), '.{}'.format(hash(os.times())))
os.makedirs(tmp)

That way you can easily clean up after yourself when you are done (for privacy, resources, security, whatever) with:

from shutil import rmtree
rmtree(tmp, ignore_errors=True)

This is similar to what applications like Google Chrome and Linux systemd do. They just use a shorter hex hash and an app-specific prefix to “advertise” their presence.


我正在运行什么操作系统?

问题:我正在运行什么操作系统?

我要查看我是在Windows还是Unix等上,我需要查看什么?

What do I need to look at to see whether I’m on Windows or Unix, etc?


回答 0

>>> import os
>>> os.name
'posix'
>>> import platform
>>> platform.system()
'Linux'
>>> platform.release()
'2.6.22-15-generic'

的输出platform.system()如下:

  • Linux: Linux
  • 苹果电脑: Darwin
  • 视窗: Windows

请参阅:platform—访问基础平台的标识数据

>>> import os
>>> os.name
'posix'
>>> import platform
>>> platform.system()
'Linux'
>>> platform.release()
'2.6.22-15-generic'

The output of platform.system() is as follows:

  • Linux: Linux
  • Mac: Darwin
  • Windows: Windows

See: platform — Access to underlying platform’s identifying data


回答 1

Dang-lbrandy击败了我,但这并不意味着我无法为您提供Vista的系统结果!

>>> import os
>>> os.name
'nt'
>>> import platform
>>> platform.system()
'Windows'
>>> platform.release()
'Vista'

…而且我不敢相信还没有人为Windows 10发布过一个:

>>> import os
>>> os.name
'nt'
>>> import platform
>>> platform.system()
'Windows'
>>> platform.release()
'10'

Dang — lbrandy beat me to the punch, but that doesn’t mean I can’t provide you with the system results for Vista!

>>> import os
>>> os.name
'nt'
>>> import platform
>>> platform.system()
'Windows'
>>> platform.release()
'Vista'

…and I can’t believe no one’s posted one for Windows 10 yet:

>>> import os
>>> os.name
'nt'
>>> import platform
>>> platform.system()
'Windows'
>>> platform.release()
'10'

回答 2

为了记录,这是在Mac上的结果:

>>> import os
>>> os.name
'posix'
>>> import platform
>>> platform.system()
'Darwin'
>>> platform.release()
'8.11.1'

For the record here’s the results on Mac:

>>> import os
>>> os.name
'posix'
>>> import platform
>>> platform.system()
'Darwin'
>>> platform.release()
'8.11.1'

回答 3

使用python区分操作系统的示例代码:

from sys import platform as _platform

if _platform == "linux" or _platform == "linux2":
    # linux
elif _platform == "darwin":
    # MAC OS X
elif _platform == "win32":
    # Windows
elif _platform == "win64":
    # Windows 64-bit

Sample code to differentiate OS’s using python:

from sys import platform as _platform

if _platform == "linux" or _platform == "linux2":
    # linux
elif _platform == "darwin":
    # MAC OS X
elif _platform == "win32":
    # Windows
elif _platform == "win64":
    # Windows 64-bit

回答 4

sys.platform如果已经导入sys并且不想导入其他模块,也可以使用

>>> import sys
>>> sys.platform
'linux2'

You can also use sys.platform if you already have imported sys and you don’t want to import another module

>>> import sys
>>> sys.platform
'linux2'

回答 5

如果您想要用户可读的数据但仍然很详细,则可以使用platform.platform()

>>> import platform
>>> platform.platform()
'Linux-3.3.0-8.fc16.x86_64-x86_64-with-fedora-16-Verne'

您可以拨打以下几种可能的电话来识别自己的位置

import platform
import sys

def linux_distribution():
  try:
    return platform.linux_distribution()
  except:
    return "N/A"

print("""Python version: %s
dist: %s
linux_distribution: %s
system: %s
machine: %s
platform: %s
uname: %s
version: %s
mac_ver: %s
""" % (
sys.version.split('\n'),
str(platform.dist()),
linux_distribution(),
platform.system(),
platform.machine(),
platform.platform(),
platform.uname(),
platform.version(),
platform.mac_ver(),
))

该脚本的输出在几种不同的系统(Linux,Windows,Solaris,MacOS)上运行,并且体系结构(x86,x64,Itanium,power pc,sparc)可在以下位置找到:https : //github.com/hpcugent/easybuild/ Wiki / OS_flavor_name_version

以Ubuntu 12.04服务器为例:

Python version: ['2.6.5 (r265:79063, Oct  1 2012, 22:04:36) ', '[GCC 4.4.3]']
dist: ('Ubuntu', '10.04', 'lucid')
linux_distribution: ('Ubuntu', '10.04', 'lucid')
system: Linux
machine: x86_64
platform: Linux-2.6.32-32-server-x86_64-with-Ubuntu-10.04-lucid
uname: ('Linux', 'xxx', '2.6.32-32-server', '#62-Ubuntu SMP Wed Apr 20 22:07:43 UTC 2011', 'x86_64', '')
version: #62-Ubuntu SMP Wed Apr 20 22:07:43 UTC 2011
mac_ver: ('', ('', '', ''), '')

If you want user readable data but still detailed, you can use platform.platform()

>>> import platform
>>> platform.platform()
'Linux-3.3.0-8.fc16.x86_64-x86_64-with-fedora-16-Verne'

Here’s a few different possible calls you can make to identify where you are

import platform
import sys

def linux_distribution():
  try:
    return platform.linux_distribution()
  except:
    return "N/A"

print("""Python version: %s
dist: %s
linux_distribution: %s
system: %s
machine: %s
platform: %s
uname: %s
version: %s
mac_ver: %s
""" % (
sys.version.split('\n'),
str(platform.dist()),
linux_distribution(),
platform.system(),
platform.machine(),
platform.platform(),
platform.uname(),
platform.version(),
platform.mac_ver(),
))

The outputs of this script ran on a few different systems (Linux, Windows, Solaris, MacOS) and architectures (x86, x64, Itanium, power pc, sparc) is available here: https://github.com/hpcugent/easybuild/wiki/OS_flavor_name_version

Ubuntu 12.04 server for example gives:

Python version: ['2.6.5 (r265:79063, Oct  1 2012, 22:04:36) ', '[GCC 4.4.3]']
dist: ('Ubuntu', '10.04', 'lucid')
linux_distribution: ('Ubuntu', '10.04', 'lucid')
system: Linux
machine: x86_64
platform: Linux-2.6.32-32-server-x86_64-with-Ubuntu-10.04-lucid
uname: ('Linux', 'xxx', '2.6.32-32-server', '#62-Ubuntu SMP Wed Apr 20 22:07:43 UTC 2011', 'x86_64', '')
version: #62-Ubuntu SMP Wed Apr 20 22:07:43 UTC 2011
mac_ver: ('', ('', '', ''), '')

回答 6

短篇故事

使用platform.system()。它返回WindowsLinuxDarwin(对于OSX)。

很长的故事

使用Python获取OS的方法有3种,每种方法各有优缺点:

方法1

>>> import sys
>>> sys.platform
'win32'  # could be 'linux', 'linux2, 'darwin', 'freebsd8' etc

工作原理(来源):内部调用OS API以获取OS定义的OS名称。有关各种特定于操作系统的值,请参见此处

优点:无魔法,低等级。

缺点:取决于操作系统版本,因此最好不要直接使用。

方法二

>>> import os
>>> os.name
'nt'  # for Linux and Mac it prints 'posix'

工作原理(来源):内部会检查python是否具有称为posix或nt的特定于操作系统的模块。

优点:易于检查posix OS

缺点:Linux或OSX之间没有区别。

方法3

>>> import platform
>>> platform.system()
'Windows' # for Linux it prints 'Linux', Mac it prints `'Darwin'

工作原理(来源):内部将最终调用内部OS API,获取特定于操作系统版本的名称,例如“ win32”或“ win16”或“ linux1”,然后将其标准化为更通用的名称,例如“ Windows”或“ Linux”或通过应用几种启发式方法来“达尔文”。

专业版:Windows,OSX和Linux的最佳便携式方式。

缺点:Python人员必须保持规范化启发式更新。

摘要

  • 如果要检查OS是Windows还是Linux或OSX,那么最可靠的方法是platform.system()
  • 如果你想OS专用电话,但通过内置的Python模块posixnt再使用os.name
  • 如果要获取OS本身提供的原始OS名称,请使用sys.platform

Short Story

Use platform.system(). It returns Windows, Linux or Darwin (for OSX).

Long Story

There are 3 ways to get OS in Python, each with its own pro and cons:

Method 1

>>> import sys
>>> sys.platform
'win32'  # could be 'linux', 'linux2, 'darwin', 'freebsd8' etc

How this works (source): Internally it calls OS APIs to get name of the OS as defined by OS. See here for various OS-specific values.

Pro: No magic, low level.

Con: OS version dependent, so best not to use directly.

Method 2

>>> import os
>>> os.name
'nt'  # for Linux and Mac it prints 'posix'

How this works (source): Internally it checks if python has OS-specific modules called posix or nt.

Pro: Simple to check if posix OS

Con: no differentiation between Linux or OSX.

Method 3

>>> import platform
>>> platform.system()
'Windows' # for Linux it prints 'Linux', Mac it prints `'Darwin'

How this works (source): Internally it will eventually call internal OS APIs, get OS version-specific name like ‘win32’ or ‘win16’ or ‘linux1’ and then normalize to more generic names like ‘Windows’ or ‘Linux’ or ‘Darwin’ by applying several heuristics.

Pro: Best portable way for Windows, OSX and Linux.

Con: Python folks must keep normalization heuristic up to date.

Summary

  • If you want to check if OS is Windows or Linux or OSX then the most reliable way is platform.system().
  • If you want to make OS-specific calls but via built-in Python modules posix or nt then use os.name.
  • If you want to get raw OS name as supplied by OS itself then use sys.platform.

回答 7

新答案如何:

import psutil
psutil.MACOS   #True (OSX is deprecated)
psutil.WINDOWS #False
psutil.LINUX   #False 

如果我正在使用MACOS,这将是输出

How about a new answer:

import psutil
psutil.MACOS   #True (OSX is deprecated)
psutil.WINDOWS #False
psutil.LINUX   #False 

This would be the output if I was using MACOS


回答 8

我开始更系统地列出了使用各种模块可以期望得到的值(可以随意编辑和添加系统):

Linux(64位)+ WSL

os.name                     posix
sys.platform                linux
platform.system()           Linux
sysconfig.get_platform()    linux-x86_64
platform.machine()          x86_64
platform.architecture()     ('64bit', '')
  • 尝试使用archlinux和mint,得到相同的结果
  • 在python2上带有sys.platform内核版本的后缀,例如linux2,其他所有内容保持不变
  • 在Linux的Windows子系统上具有相同的输出(与ubuntu 18.04 LTS一起尝试),除了 platform.architecture() = ('64bit', 'ELF')

WINDOWS(64位)

(其中32bit列在32bit子系统中运行)

official python installer   64bit                     32bit
-------------------------   -----                     -----
os.name                     nt                        nt
sys.platform                win32                     win32
platform.system()           Windows                   Windows
sysconfig.get_platform()    win-amd64                 win32
platform.machine()          AMD64                     AMD64
platform.architecture()     ('64bit', 'WindowsPE')    ('64bit', 'WindowsPE')

msys2                       64bit                     32bit
-----                       -----                     -----
os.name                     posix                     posix
sys.platform                msys                      msys
platform.system()           MSYS_NT-10.0              MSYS_NT-10.0-WOW
sysconfig.get_platform()    msys-2.11.2-x86_64        msys-2.11.2-i686
platform.machine()          x86_64                    i686
platform.architecture()     ('64bit', 'WindowsPE')    ('32bit', 'WindowsPE')

msys2                       mingw-w64-x86_64-python3  mingw-w64-i686-python3
-----                       ------------------------  ----------------------
os.name                     nt                        nt
sys.platform                win32                     win32
platform.system()           Windows                   Windows
sysconfig.get_platform()    mingw                     mingw
platform.machine()          AMD64                     AMD64
platform.architecture()     ('64bit', 'WindowsPE')    ('32bit', 'WindowsPE')

cygwin                      64bit                     32bit
------                      -----                     -----
os.name                     posix                     posix
sys.platform                cygwin                    cygwin
platform.system()           CYGWIN_NT-10.0            CYGWIN_NT-10.0-WOW
sysconfig.get_platform()    cygwin-3.0.1-x86_64       cygwin-3.0.1-i686
platform.machine()          x86_64                    i686
platform.architecture()     ('64bit', 'WindowsPE')    ('32bit', 'WindowsPE')

一些说明:

  • 也有distutils.util.get_platform()和`sysconfig.get_platform
  • Windows上的anaconda与官方python Windows安装程序相同
  • 我没有Mac,也没有真正的32位系统,也没有动力在线​​进行此操作

要与您的系统进行比较,只需运行此脚本(如果缺少,请在此处附加结果:)

from __future__ import print_function
import os
import sys
import platform
import sysconfig

print("os.name                      ",  os.name)
print("sys.platform                 ",  sys.platform)
print("platform.system()            ",  platform.system())
print("sysconfig.get_platform()     ",  sysconfig.get_platform())
print("platform.machine()           ",  platform.machine())
print("platform.architecture()      ",  platform.architecture())

I started a bit more systematic listing of what values you can expect using the various modules (feel free to edit and add your system):

Linux (64bit) + WSL

os.name                     posix
sys.platform                linux
platform.system()           Linux
sysconfig.get_platform()    linux-x86_64
platform.machine()          x86_64
platform.architecture()     ('64bit', '')
  • tried with archlinux and mint, got same results
  • on python2 sys.platform is suffixed by kernel version, e.g. linux2, everything else stays identical
  • same output on Windows Subsystem for Linux (tried with ubuntu 18.04 LTS), except platform.architecture() = ('64bit', 'ELF')

WINDOWS (64bit)

(with 32bit column running in the 32bit subsystem)

official python installer   64bit                     32bit
-------------------------   -----                     -----
os.name                     nt                        nt
sys.platform                win32                     win32
platform.system()           Windows                   Windows
sysconfig.get_platform()    win-amd64                 win32
platform.machine()          AMD64                     AMD64
platform.architecture()     ('64bit', 'WindowsPE')    ('64bit', 'WindowsPE')

msys2                       64bit                     32bit
-----                       -----                     -----
os.name                     posix                     posix
sys.platform                msys                      msys
platform.system()           MSYS_NT-10.0              MSYS_NT-10.0-WOW
sysconfig.get_platform()    msys-2.11.2-x86_64        msys-2.11.2-i686
platform.machine()          x86_64                    i686
platform.architecture()     ('64bit', 'WindowsPE')    ('32bit', 'WindowsPE')

msys2                       mingw-w64-x86_64-python3  mingw-w64-i686-python3
-----                       ------------------------  ----------------------
os.name                     nt                        nt
sys.platform                win32                     win32
platform.system()           Windows                   Windows
sysconfig.get_platform()    mingw                     mingw
platform.machine()          AMD64                     AMD64
platform.architecture()     ('64bit', 'WindowsPE')    ('32bit', 'WindowsPE')

cygwin                      64bit                     32bit
------                      -----                     -----
os.name                     posix                     posix
sys.platform                cygwin                    cygwin
platform.system()           CYGWIN_NT-10.0            CYGWIN_NT-10.0-WOW
sysconfig.get_platform()    cygwin-3.0.1-x86_64       cygwin-3.0.1-i686
platform.machine()          x86_64                    i686
platform.architecture()     ('64bit', 'WindowsPE')    ('32bit', 'WindowsPE')

Some remarks:

  • there is also distutils.util.get_platform() which is identical to `sysconfig.get_platform
  • anaconda on windows is same as official python windows installer
  • I don’t have a Mac nor a true 32bit system and was not motivated to do it online

To compare with your system, simply run this script (and please append results here if missing :)

from __future__ import print_function
import os
import sys
import platform
import sysconfig

print("os.name                      ",  os.name)
print("sys.platform                 ",  sys.platform)
print("platform.system()            ",  platform.system())
print("sysconfig.get_platform()     ",  sysconfig.get_platform())
print("platform.machine()           ",  platform.machine())
print("platform.architecture()      ",  platform.architecture())

回答 9

我使用的是weblogic附带的WLST工具,它没有实现平台软件包。

wls:/offline> import os
wls:/offline> print os.name
java 
wls:/offline> import sys
wls:/offline> print sys.platform
'java1.5.0_11'

除了修补系统javaos.py使用jdk1.5在Windows 2003上的os.system()问题)补丁(我不能做,我必须开箱即用使用weblogic),这是我使用的方法:

def iswindows():
  os = java.lang.System.getProperty( "os.name" )
  return "win" in os.lower()

I am using the WLST tool that comes with weblogic, and it doesn’t implement the platform package.

wls:/offline> import os
wls:/offline> print os.name
java 
wls:/offline> import sys
wls:/offline> print sys.platform
'java1.5.0_11'

Apart from patching the system javaos.py (issue with os.system() on windows 2003 with jdk1.5) (which I can’t do, I have to use weblogic out of the box), this is what I use:

def iswindows():
  os = java.lang.System.getProperty( "os.name" )
  return "win" in os.lower()

回答 10

/usr/bin/python3.2

def cls():
    from subprocess import call
    from platform import system

    os = system()
    if os == 'Linux':
        call('clear', shell = True)
    elif os == 'Windows':
        call('cls', shell = True)

/usr/bin/python3.2

def cls():
    from subprocess import call
    from platform import system

    os = system()
    if os == 'Linux':
        call('clear', shell = True)
    elif os == 'Windows':
        call('cls', shell = True)

回答 11

对于Jython,我发现获得操作系统名称的唯一方法是检查os.nameJava属性(在WinXP上使用sysosplatformJython 2.5.3的模块进行了尝试):

def get_os_platform():
    """return platform name, but for Jython it uses os.name Java property"""
    ver = sys.platform.lower()
    if ver.startswith('java'):
        import java.lang
        ver = java.lang.System.getProperty("os.name").lower()
    print('platform: %s' % (ver))
    return ver

For Jython the only way to get os name I found is to check os.name Java property (tried with sys, os and platform modules for Jython 2.5.3 on WinXP):

def get_os_platform():
    """return platform name, but for Jython it uses os.name Java property"""
    ver = sys.platform.lower()
    if ver.startswith('java'):
        import java.lang
        ver = java.lang.System.getProperty("os.name").lower()
    print('platform: %s' % (ver))
    return ver

回答 12

在Windows 8上有趣的结果:

>>> import os
>>> os.name
'nt'
>>> import platform
>>> platform.system()
'Windows'
>>> platform.release()
'post2008Server'

编辑:那是一个错误

Interesting results on windows 8:

>>> import os
>>> os.name
'nt'
>>> import platform
>>> platform.system()
'Windows'
>>> platform.release()
'post2008Server'

Edit: That’s a bug


回答 13

当心,如果你使用的是Windows使用Cygwin哪里os.nameposix

>>> import os, platform
>>> print os.name
posix
>>> print platform.system()
CYGWIN_NT-6.3-WOW

Watch out if you’re on Windows with Cygwin where os.name is posix.

>>> import os, platform
>>> print os.name
posix
>>> print platform.system()
CYGWIN_NT-6.3-WOW

回答 14

以同样的方式…

import platform
is_windows=(platform.system().lower().find("win") > -1)

if(is_windows): lv_dll=LV_dll("my_so_dll.dll")
else:           lv_dll=LV_dll("./my_so_dll.so")

in the same vein….

import platform
is_windows=(platform.system().lower().find("win") > -1)

if(is_windows): lv_dll=LV_dll("my_so_dll.dll")
else:           lv_dll=LV_dll("./my_so_dll.so")

回答 15

如果您不是在寻找内核版本等,而是在寻找Linux发行版,则可能需要使用以下代码

在python2.6 +中

>>> import platform
>>> print platform.linux_distribution()
('CentOS Linux', '6.0', 'Final')
>>> print platform.linux_distribution()[0]
CentOS Linux
>>> print platform.linux_distribution()[1]
6.0

在python2.4中

>>> import platform
>>> print platform.dist()
('centos', '6.0', 'Final')
>>> print platform.dist()[0]
centos
>>> print platform.dist()[1]
6.0

显然,这只有在Linux上运行时才有效。如果希望跨平台使用更通用的脚本,可以将其与其他答案中给出的代码示例混合使用。

If you not looking for the kernel version etc, but looking for the linux distribution you may want to use the following

in python2.6+

>>> import platform
>>> print platform.linux_distribution()
('CentOS Linux', '6.0', 'Final')
>>> print platform.linux_distribution()[0]
CentOS Linux
>>> print platform.linux_distribution()[1]
6.0

in python2.4

>>> import platform
>>> print platform.dist()
('centos', '6.0', 'Final')
>>> print platform.dist()[0]
centos
>>> print platform.dist()[1]
6.0

Obviously, this will work only if you are running this on linux. If you want to have more generic script across platforms, you can mix this with code samples given in other answers.


回答 16

尝试这个:

import os

os.uname()

你可以做到:

info=os.uname()
info[0]
info[1]

try this:

import os

os.uname()

and you can make it :

info=os.uname()
info[0]
info[1]

回答 17

使用模块平台检查可用的测试,并为您的系统打印答案:

import platform

print dir(platform)

for x in dir(platform):
    if x[0].isalnum():
        try:
            result = getattr(platform, x)()
            print "platform."+x+": "+result
        except TypeError:
            continue

Check the available tests with module platform and print the answer out for your system:

import platform

print dir(platform)

for x in dir(platform):
    if x[0].isalnum():
        try:
            result = getattr(platform, x)()
            print "platform."+x+": "+result
        except TypeError:
            continue

回答 18

您也可以仅使用平台模块,而无需导入os模块来获取所有信息。

>>> import platform
>>> platform.os.name
'posix'
>>> platform.uname()
('Darwin', 'mainframe.local', '15.3.0', 'Darwin Kernel Version 15.3.0: Thu Dec 10 18:40:58 PST 2015; root:xnu-3248.30.4~1/RELEASE_X86_64', 'x86_64', 'i386')

使用此行可以实现一个美观,整洁的报告布局:

for i in zip(['system','node','release','version','machine','processor'],platform.uname()):print i[0],':',i[1]

给出以下输出:

system : Darwin
node : mainframe.local
release : 15.3.0
version : Darwin Kernel Version 15.3.0: Thu Dec 10 18:40:58 PST 2015; root:xnu-3248.30.4~1/RELEASE_X86_64
machine : x86_64
processor : i386

通常缺少的是操作系统版本,但是您应该知道是运行Windows,Linux还是Mac,平台独立的方式是使用此测试:

In []: for i in [platform.linux_distribution(),platform.mac_ver(),platform.win32_ver()]:
   ....:     if i[0]:
   ....:         print 'Version: ',i[0]

You can also use only platform module without importing os module to get all the information.

>>> import platform
>>> platform.os.name
'posix'
>>> platform.uname()
('Darwin', 'mainframe.local', '15.3.0', 'Darwin Kernel Version 15.3.0: Thu Dec 10 18:40:58 PST 2015; root:xnu-3248.30.4~1/RELEASE_X86_64', 'x86_64', 'i386')

A nice and tidy layout for reporting purpose can be achieved using this line:

for i in zip(['system','node','release','version','machine','processor'],platform.uname()):print i[0],':',i[1]

That gives this output:

system : Darwin
node : mainframe.local
release : 15.3.0
version : Darwin Kernel Version 15.3.0: Thu Dec 10 18:40:58 PST 2015; root:xnu-3248.30.4~1/RELEASE_X86_64
machine : x86_64
processor : i386

What is missing usually is the operating system version but you should know if you are running windows, linux or mac a platform indipendent way is to use this test:

In []: for i in [platform.linux_distribution(),platform.mac_ver(),platform.win32_ver()]:
   ....:     if i[0]:
   ....:         print 'Version: ',i[0]

回答 19

我知道这是一个古老的问题,但我相信我的回答可能对某些正在寻找一种简单,易于理解的python方法在其代码中检测OS的人有所帮助。在python3.7上测试

from sys import platform


class UnsupportedPlatform(Exception):
    pass


if "linux" in platform:
    print("linux")
elif "darwin" in platform:
    print("mac")
elif "win" in platform:
    print("windows")
else:
    raise UnsupportedPlatform

I know this is an old question but I believe that my answer is one that might be helpful to some people who are looking for an easy, simple to understand pythonic way to detect OS in their code. Tested on python3.7

from sys import platform


class UnsupportedPlatform(Exception):
    pass


if "linux" in platform:
    print("linux")
elif "darwin" in platform:
    print("mac")
elif "win" in platform:
    print("windows")
else:
    raise UnsupportedPlatform

回答 20

如果您正在运行macOS X并运行,platform.system()则会得到darwin,因为macOS X是基于Apple的Darwin OS构建的。Darwin是macOS X的内核,本质上是没有GUI的macOSX。

If you are running macOS X and run platform.system() you get darwin because macOS X is built on Apple’s Darwin OS. Darwin is the kernel of macOS X and is essentially macOS X without the GUI.


回答 21

此解决方案适用于pythonjython

模块os_identify.py

import platform
import os

# This module contains functions to determine the basic type of
# OS we are running on.
# Contrary to the functions in the `os` and `platform` modules,
# these allow to identify the actual basic OS,
# no matter whether running on the `python` or `jython` interpreter.

def is_linux():
    try:
        platform.linux_distribution()
        return True
    except:
        return False

def is_windows():
    try:
        platform.win32_ver()
        return True
    except:
        return False

def is_mac():
    try:
        platform.mac_ver()
        return True
    except:
        return False

def name():
    if is_linux():
        return "Linux"
    elif is_windows():
        return "Windows"
    elif is_mac():
        return "Mac"
    else:
        return "<unknown>" 

像这样使用:

import os_identify

print "My OS: " + os_identify.name()

This solution works for both python and jython.

module os_identify.py:

import platform
import os

# This module contains functions to determine the basic type of
# OS we are running on.
# Contrary to the functions in the `os` and `platform` modules,
# these allow to identify the actual basic OS,
# no matter whether running on the `python` or `jython` interpreter.

def is_linux():
    try:
        platform.linux_distribution()
        return True
    except:
        return False

def is_windows():
    try:
        platform.win32_ver()
        return True
    except:
        return False

def is_mac():
    try:
        platform.mac_ver()
        return True
    except:
        return False

def name():
    if is_linux():
        return "Linux"
    elif is_windows():
        return "Windows"
    elif is_mac():
        return "Mac"
    else:
        return "<unknown>" 

Use like this:

import os_identify

print "My OS: " + os_identify.name()

回答 22

像下面这样的简单Enum实现如何?无需外部库!

import platform
from enum import Enum
class OS(Enum):
    def checkPlatform(osName):
        return osName.lower()== platform.system().lower()

    MAC = checkPlatform("darwin")
    LINUX = checkPlatform("linux")
    WINDOWS = checkPlatform("windows")  #I haven't test this one

只需您即可使用Enum值进行访问

if OS.LINUX.value:
    print("Cool it is Linux")

PS是python3

How about a simple Enum implementation like the following? No need for external libs!

import platform
from enum import Enum
class OS(Enum):
    def checkPlatform(osName):
        return osName.lower()== platform.system().lower()

    MAC = checkPlatform("darwin")
    LINUX = checkPlatform("linux")
    WINDOWS = checkPlatform("windows")  #I haven't test this one

Simply you can access with Enum value

if OS.LINUX.value:
    print("Cool it is Linux")

P.S It is python3


回答 23

您可以查看pyOSinfo其中的代码是pip-date的一部分软件包,以获取最相关的系统信息,从你的Python分布观察。

人们想要检查其操作系统的最常见原因之一是终端兼容性以及某些系统命令是否可用。不幸的是,此检查的成功在某种程度上取决于您的python安装和操作系统。例如,uname在大多数Windows python软件包中不可用。上面的python程序将向您显示已经提供的最常用的内置函数的输出os, sys, platform, site

因此,仅获取基本代码的最佳方法就是以为例。(我想我可以将其粘贴到这里,但是从政治上讲这不是正确的。)

You can look at the code in pyOSinfo which is part of the pip-date package, to get the most relevant OS information, as seen from your Python distribution.

One of the most common reasons people want to check their OS is for terminal compatibility and if certain system commands are available. Unfortunately, the success of this checking is somewhat dependent on your python installation and OS. For example, uname is not available on most Windows python packages. The above python program will show you the output of the most commonly used built-in functions, already provided by os, sys, platform, site.

So the best way to get only the essential code is looking at that as an example. (I guess I could have just pasted it here, but that would not have been politically correct.)


回答 24

我迟到了游戏,但是,以防万一有人需要它,我使用此函数来调整我的代码,使其可以在Windows,Linux和MacO上运行:

import sys
def get_os(osoptions={'linux':'linux','Windows':'win','macos':'darwin'}):
    '''
    get OS to allow code specifics
    '''   
    opsys = [k for k in osoptions.keys() if sys.platform.lower().find(osoptions[k].lower()) != -1]
    try:
        return opsys[0]
    except:
        return 'unknown_OS'

I am late to the game but, just in case anybody needs it, this a function I use to make adjustments on my code so it runs on Windows, Linux and MacOs:

import sys
def get_os(osoptions={'linux':'linux','Windows':'win','macos':'darwin'}):
    '''
    get OS to allow code specifics
    '''   
    opsys = [k for k in osoptions.keys() if sys.platform.lower().find(osoptions[k].lower()) != -1]
    try:
        return opsys[0]
    except:
        return 'unknown_OS'

如何在Python中获取主目录?

问题:如何在Python中获取主目录?

我需要获取当前登录用户的主目录的位置。当前,我在Linux上一直使用以下命令:

os.getenv("HOME")

但是,这在Windows上不起作用。正确的跨平台方法是什么?

I need to get the location of the home directory of the current logged-on user. Currently, I’ve been using the following on Linux:

os.getenv("HOME")

However, this does not work on Windows. What is the correct cross-platform way to do this?


回答 0

您要使用os.path.expanduser
这将确保它可在所有平台上运行:

from os.path import expanduser
home = expanduser("~")

如果您使用的是Python 3.5+,则可以使用pathlib.Path.home()

from pathlib import Path
home = str(Path.home())

You want to use os.path.expanduser.
This will ensure it works on all platforms:

from os.path import expanduser
home = expanduser("~")

If you’re on Python 3.5+ you can use pathlib.Path.home():

from pathlib import Path
home = str(Path.home())

回答 1

这是一种Linux方式cd ..如果您需要使用它,请注意:(如果位于子目录中,它将进入该目录)

Here is a linux way cd .. if you need to use that instead note:(if you are in a sub directory then it will take to the directory)


Youtube-dl-gui-用wxPython编写的流行的youtube-dl的跨平台前端GUI

一款流行的跨平台前端GUIyoutube-dl用wxPython编写的媒体下载器。Supported sites

屏幕截图

要求

下载次数

安装

从源安装

  1. 下载并解压缩源代码
  2. 将目录更改为youtube-dl-gui-0.4
  3. python setup.py install

安装PyPi

  1. pip install youtube-dlg

安装Windows Installer

  1. 下载并解压缩Windows Installer
  2. 运行setup.exe文件

贡献

作者

看见AUTHORS文件

许可证

这个Public Domain License

常见问题解答

看见FAQs文件

谢谢

感谢为这个项目做出贡献的每一个人,感谢@philipzae用于设计新的UI布局

Flatbuffers-FlatBuffers:内存效率高的串行化库

Flatbuffers

Flatbuffers是一个跨平台的序列化库,旨在实现最高的内存效率。它允许您直接访问序列化数据,而无需先对其进行解析/解包,同时仍具有很好的向前/向后兼容性

请访问我们的landing page浏览我们的文档

支持的操作系统

  • Windows
  • MacOS X
  • Linux操作系统
  • 安卓系统
  • 以及使用最新的C++编译器的任何其他版本

支持的编程语言

  • C++
  • C#
  • C
  • GO
  • Java语言
  • JavaScript
  • PHP
  • python
  • Rust

还有更多的正在进行中

贡献

为这个项目做贡献,看见CONTRIBUTING

安全性

请参阅我们的Security Policy用于报告漏洞

许可

平缓冲器是按照Apache许可证2.0版进行许可的。看见LICENSE有关完整的许可证文本,请参阅