python能检测到它在哪个操作系统下运行吗?
python可以检测操作系统,然后为文件系统构造一个if/else语句 我需要将Fn字符串中的C:\CobaltRCX\替换为FileSys字符串python能检测到它在哪个操作系统下运行吗?,python,windows,linux,Python,Windows,Linux,python可以检测操作系统,然后为文件系统构造一个if/else语句 我需要将Fn字符串中的C:\CobaltRCX\替换为FileSys字符串 import os.path, csv from time import strftime if os.path.?????:## Windows FileSys = r"C:\\working\\" else: ##linux FileSys = r"\\working\\" y=(strftime("%y%m%d")
import os.path, csv
from time import strftime
if os.path.?????:## Windows
FileSys = r"C:\\working\\"
else: ##linux
FileSys = r"\\working\\"
y=(strftime("%y%m%d"))
Fn = (r"C:\\working\\Setup%s.csv" %y)
使用
sys.platform
。您可以在这里找到更多信息我通常只使用以下内容:
import os
if os.name == 'nt':
pass # Windows
else:
pass # other (unix)
编辑:
希望对您的评论作出回应:
from time import strftime
import os
if os.name == 'nt': # Windows
basePath = 'C:\\working\\'
else:
basePath = '/working/'
Fn = '%sSetup%s.csv' % ( basePath, strftime( '%y%m%d' ) )
你可以看看os.uname
In [12]: os.uname()
Out[12]:
('Darwin',
'demitasse.local',
'10.6.0',
'Darwin Kernel Version 10.6.0: Wed Nov 10 18:13:17 PST 2010; root:xnu-1504.9.26~3/RELEASE_I386',
'i386')
对
对于大多数用例,您应该使用该模块。但是,如果您需要更精简的界面,请尝试。尝试此界面:
import platform
platform.uname()
它可以在linux和windows上工作。仅供参考:os.uname()在windows上不起作用,尽管它在linux上起作用。平台是通用的 这是我前几天刚刚创建的内容: 代码:
def GetUserPlatform():
if sys.platform == 'win32':
UsrWinVer = str(sys.getwindowsversion().major)
print("Operating System: Windows " + UsrWinVer)
else:
print("Something else")
GetUserPlatform()
输出:
def GetUserPlatform():
if sys.platform == 'win32':
UsrWinVer = str(sys.getwindowsversion().major)
print("Operating System: Windows " + UsrWinVer)
else:
print("Something else")
GetUserPlatform()
操作系统:Windows 10
这将为您提供Windows、Linux等的最新答案,但如果您试图确定路径分隔符,您可以使用
os.path.sep
请看这里:
您可以查看我的github repo并使用pyos.py脚本platform.system()==platform.uname()[0]==Windows,是吗?这是什么意思?Fn字符串“C:\\working\\Setup%s.csv”。第二个变量将如何使用。1,文件是第2个y日期。现在我已经有了日期设置,需要关于“filesys”yada yada yada“date”字符串的帮助。谢谢,我不确定我现在是否用编辑来回答它,但我真的不明白。请尝试用综合英语解释,否则…是的,当然,对不起。如果路径变得比这更复杂,您还可以使用os.path连接多个路径序列。
platform.system()
比sys.platform
更一致/可靠。看见
os.path.sep
import platform
plt = platform.system()
if plt == "Windows": print("Your system is Windows")
elif plt == "Linux": print("Your system is Linux")
elif plt == "Darwin": print("Your system is MacOS")
else: print("Unidentified system")