如何用Python将程序添加到PATH中?
我有一个程序,它会安装一个文件夹,我希望这个文件夹在下载后能自动添加到系统的路径中。
这是我的代码。
import os
import requests
import zipfile
import shutil
def download_file(url, save_path):
# Download the file from the URL
response = requests.get(url)
with open(save_path, 'wb') as file:
file.write(response.content)
def extract_zip(zip_path, extract_path):
# Extract the contents of the ZIP file
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
zip_ref.extractall(extract_path)
def add_to_path(directory):
# Add the directory containing "insulter.exe" to the PATH environment variable
insulter_directory = os.path.join(directory, "Insult-CLI-build")
os.environ['PATH'] += os.pathsep + insulter_directory
def main():
# URL of the file to download
file_url = 'https://github.com/my2religion2is2sillyism2imma2sillybilly/Insult-CLI/archive/refs/heads/build.zip'
# Directory where the file will be saved and extracted
current_directory = os.getcwd()
# Download the file
file_name = file_url.split('/')[-1]
save_path = os.path.join(current_directory, file_name)
download_file(file_url, save_path)
# Extract the file
if file_name.endswith('.zip'):
extract_zip(save_path, current_directory)
# Add the extracted directory to the PATH
add_to_path(current_directory)
print("File downloaded and added to PATH successfully!")
if __name__ == "__main__":
main()
它说已经成功添加到路径了,但实际上只是安装并解压了这个文件夹。
1 个回答
0
试试这个。
def add_to_path(directory):
variable
insulter_directory = os.path.join(directory, "Insult-CLI-build")
os.environ['PATH'] = insulter_directory + os.pathsep + os.environ['PATH']
另外,确保解压后的文件夹结构符合你的预期,并且在 Insult-CLI-build 这个文件夹里确实存在 insult.exe 这个文件。