gpt4 book ai didi

python - 使用python查找用户目录

转载 作者:太空宇宙 更新时间:2023-11-04 08:24:48 24 4
gpt4 key购买 nike

所以我正在编写一个脚本来自动化我和我的队友所做的一些事情。我们有一个 git repo,这个脚本是供所有成员使用的。它有一个部分被硬编码为我的文件夹路径:C:/Users/jorge.padilla/etc...

我对 python 还是比较陌生,不熟悉所有不同的库。我基本上想将用户目录(即 jorge.padilla)变成一个非硬编码的变量,并且不需要接受用户输入,以便脚本将搜索当前用户目录并替换它。

下面是我正在编写的自动化脚本的一小段,用作示例。

import os, sys
from pathlib import Path
from enum import Enum

#Global Variables
PRODUCTS_FOLDER = "Products"
APP_FOLDER = "App"
DEV_BUILD = "ionic cordova build android"
PROD_BUILD = "ionic cordova build android --release --prod"

class BuildConfig():
def __init__(self, start_path):
self.start_path = start_path

def getProductFolder(self):
return os.path.join(self.start_path, PRODUCTS_FOLDER)

class BuildTypeEnum(Enum):
PROD = 1
DEV = 2

def buildingApp(ConfigPath:BuildConfig, DEVvPROD:BuildTypeEnum):
path = ConfigPath.getProductFolder()
app_path = os.path.join(path, APP_FOLDER)
os.chdir(app_path)
if DEVvPROD == BuildTypeEnum.DEV:
os.system(DEV_BUILD)
elif DEVvPROD == BuildTypeEnum.PROD:
os.system(PROD_BUILD)
else:
print("Invalid input.")
return

if __name__ == "__main__":
root_start_path = "C:/Users/jorge.padilla/Documents/"
build = BuildConfig(root_start_path)

buildType = None
buildTypeInput = input("Is this a dev or production build? (d/p): ")
if (buildTypeInput.lower() == 'd'):
buildType = BuildTypeEnum.DEV
elif (buildTypeInput.lower() == 'p'):
buildType = BuildTypeEnum.PROD
else:
print("Please specify if this is a development or production build.")
return

我要为其执行此操作的主要变量是 root_start_path

最佳答案

你应该使用 pathlib (您导入但从未使用过的?):

import pathlib
root_start_path = pathlib.Path.home() # WindowsPath('C:/Users/jorge.padilla')

它也适用于跨平台,它确实是处理文件路径的最佳方式 (IMO)

它甚至可以简化访问该路径中其他目录的语法:

root_start_path = pathlib.Path.home() / 'Documents'  # WindowsPath('C:/Users/jorge.padilla/Documents')

关于python - 使用python查找用户目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58420681/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com