简体   繁体   English

如何在 Python 中引用一个目录,使其在多台计算机上工作?

[英]How do I reference a directory in Python so it works on multiple computers?

I created a Python script that I want to use on different computers.我创建了一个要在不同计算机上使用的 Python 脚本。 I'm using os and pyautogui modules since for pyautogui I have multiple screenshots stored in the folder where py python script is located, also I have a .txt file from which I grab information relevant to the script and should be different on each of those computers.我正在使用 os 和 pyautogui 模块,因为对于 pyautogui 我有多个屏幕截图存储在 py python 脚本所在的文件夹中,我还有一个 .txt 文件,我从中获取与脚本相关的信息,并且每个文件都应该不同电脑。 This is the reference in the script:这是脚本中的引用:

os.chdir(r'C:\Users\myusername\Desktop\Script')
p.FAILSAFE = False

# extracts login and password from a txt file, for each user
credentials = open("login.txt", "r")
for line in credentials:
    pieces = line.split(":")
    email = pieces[0]
    password = pieces[1]

How do I make it accustom to any computer where the script is located and will it work with pyinstaller after I converted the .py file into .exe.我如何使它适应脚本所在的任何计算机,并且在我将 .py 文件转换为 .exe 后它是否可以与 pyinstaller 一起使用。 Thanks!谢谢!

You can create a directory and point to it, the code will be:您可以创建一个目录并指向它,代码将是:

directory_path = os.path.join(os.environ['USERPROFILE'],'Desktop','Script')
if not os.path.isdir(directory_path): os.mkdir(directory_path)

os.environ['USERPROFILE'] gets the user directory for each user in each machine. os.environ['USERPROFILE']获取每台机器中每个用户的用户目录。

You can use os.path.expanduser to reference user home directory.您可以使用os.path.expanduser来引用用户主目录。 This will work in Unix and Windows.这将适用于 Unix 和 Windows。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何找到根目录以便路径可以在多台计算机上运行? - How do you find the root directory so that a path works across multiple computers? 如何在Python代码中修改文件路径,使其在其他计算机上工作? - How to modify a filepath in Python code so that it works on other computers? 如何检查目录是否存在,然后检查是否在Python中提供了新的目录名称? - How do I check if a directory exists and then, if so, ask for a new directory name in Python? 如何保护我的Python代码库,以便访客无法看到某些模块,但仍然有效? - How do I protect my Python codebase so that guests can't see certain modules but so it still works? 添加到:如何保护我的Python代码库,以便访客无法查看某些模块,但仍然有效? - Add on to: How do I protect my Python codebase so that guests can't see certain modules but so it still works? 如何更改python中的目录,使其在运行脚本后保持不变? - How do I change directory in python so it remains after running the script? Python:如何创建对引用的引用? - Python: How do I create a reference to a reference? Python中的多重继承; 用Java怎么做? - Multiple inheritance in Python; how to do so in Java? 记录执行时间:计算机如何快速计算出算术? - Recording time of execution: How do computers calculate arithemetic so fast? 如果我计划运行一个使用pyautogui的python脚本,它可以一次运行多台计算机还是只能运行一台? - If I plan to run a python script that uses pyautogui can it do multiple computers at once or only one?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM