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 fileprint f.read()# reads data back from the file
f.close()# temporary file is automatically deleted here
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:
The directory named by the TMPDIR environment variable.
The directory named by the TEMP environment variable.
The directory named by the TMP environment variable.
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.
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.
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.
from sys import platform as _platform
if _platform =="linux"or _platform =="linux2":# linuxelif _platform =="darwin":# MAC OS Xelif _platform =="win32":# Windowselif _platform =="win64":# Windows 64-bit
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
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.
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)
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)
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'
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.
import platform
print dir(platform)for x in dir(platform):if x[0].isalnum():try:
result = getattr(platform, x)()print"platform."+x+": "+result
exceptTypeError: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 :DarwinKernelVersion15.3.0:ThuDec1018:40:58 PST 2015; root:xnu-3248.30.4~1/RELEASE_X86_64
machine : x86_64
processor : 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]
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
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
此解决方案适用于python和jython。
模块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()returnTrueexcept:returnFalsedef is_windows():try:
platform.win32_ver()returnTrueexcept:returnFalsedef is_mac():try:
platform.mac_ver()returnTrueexcept:returnFalsedef name():if is_linux():return"Linux"elif is_windows():return"Windows"elif is_mac():return"Mac"else:return"<unknown>"
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 importEnumclass 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
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
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.)
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'