简体   繁体   English

我如何让 os.getcwd() 从 .py 文件和运行(Win + R)中获得相同的行为

[英]How do I get os.getcwd() to Act Identical from .py File and Run(Win+R)

I have a Python script and I use os.getcwd When I run it from "run"(windows+r) it goes to my user profile.我有一个 Python 脚本,我使用os.getcwd当我从“run”(windows+r) 运行它时,它会转到我的用户配置文件。 when I run it from the .py file it goes to "C:\\python34", which is what I want.当我从 .py 文件运行它时,它会转到“C:\\python34”,这就是我想要的。 How to I get them to do the same thing, which is to go to my Python folder.如何让他们做同样的事情,也就是转到我的 Python 文件夹。

script:脚本:

#!python3
import os
current=os.getcwd()
os.startfile(current)

There's not enough information provided for me to know why you're getting inconsistent results.没有提供足够的信息让我知道为什么你得到不一致的结果。 I can only guess.我只能猜测。

I do know that you're not going to get what you want using os.getcwd() .我知道你不会使用os.getcwd()得到你想要的东西。 In Windows, when using the Run dialog, it uses the %USERPROFILE% environment variable to set the C urrent W orking D irectory.在Windows中,使用时Run对话框,它使用%USERPROFILE%环境变量来设置C urrent w ^ d工作会有irectory。 If you execute the script from a different directory, os.getcwd() will return the directory you're in not the directory the script is in.如果您从不同的目录执行脚本, os.getcwd()将返回您所在的目录,而不是脚本所在的目录。

I would suggest using something like the following to accomplish your goal.我建议使用以下内容来实现您的目标。 It should open up Explorer passing in the folder where Python is installed (the version you're executing the script with):它应该打开资源管理器,传入安装 Python 的文件夹(您正在执行脚本的版本):

#!python3
import os, sys
os.startfile(sys.prefix)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM