简体   繁体   English

Python程序需要Notepad ++中的完整路径

[英]Python program needs full path in Notepad++

Not a major issue but just an annoyance I've come upon while doing class work. 这不是主要问题,只是我在上课时遇到的烦恼。 I have my Notepad++ set up to run Python code straight from Notepad++ but I've noticed when trying to access files I have to use the full path to the file even given the source text file is in the same folder as the Python program being run. 我已经将Notepad ++设置为直接从Notepad ++运行Python代码,但是我注意到在尝试访问文件时,即使源文本文件与正在运行的Python程序位于同一文件夹中,我也必须使用文件的完整路径。

However, when running my Python program through cmd I can just type in the specific file name sans the entire path. 但是,通过cmd运行我的Python程序时,我只需输入没有整个路径的特定文件名即可。

Does anyone have a short answer as to why this might be or maybe how to reconfigure Notepad++? 是否有人对此有一个简短的答案,或者可能是如何重新配置​​Notepad ++?

Thanks in advance. 提前致谢。

The problem is that your code is assuming that the current working directory is the same as the script directory. 问题是您的代码假定当前工作目录与脚本目录相同。 This is not true in general. 通常这是不正确的。 Of course it is true if you're in a cmd window, and you cd to the script directory before running it. 当然,如果您在cmd窗口中,并且在运行脚本之前将其cd到脚本目录,则为true。

If you don't want to rely on that (eg, because you want to be able to run scripts from Notepad++, or directly from Explorer), what you want to do is use the script directory explicitly. 如果您不想依靠它(例如,因为您希望能够从Notepad ++或直接从资源管理器运行脚本),则要做的是显式使用脚本目录。 For example: 例如:

import os
import sys

scriptdir = os.path.abspath(os.path.dirname(sys.argv[0]))

with open(os.path.join(scriptdir, 'myfile.txt')) as f:
    # etc.

If you have a ton of files that your scripts reference in a ton of places, it might be better to explicitly set the working directory. 如果脚本中引用了大量文件,那么最好显式设置工作目录。 Just add one line: 只需添加一行:

os.chdir(scriptdir)

For anything beyond quick&dirty scripts, it's usually better to build an installable package and use pkg_resources to access the data files. 对于快速和肮脏的脚本以外的任何内容,通常最好构建一个可安装的程序包并使用pkg_resources访问数据文件。 Read the Tutorial on Packaging and Distributing Projects for more details. 阅读包装和分发项目教程以获取更多详细信息。 But as long as you're only hacking up scripts to help you maintain your specific system, the scriptdir solution is workable. 但是,只要您只是破解脚本来帮助您维护特定的系统,scriptdir解决方案就是可行的。

In the properties of the shortcut that you use to start Notepad++, you can change its working directory, to whichever directory you're more accustomed to starting from in Python. 在用于启动Notepad ++的快捷方式的属性中,可以将其工作目录更改为您更习惯于从Python开始的目录。 You can also begin your python program with the appropriate os.chdir() command. 您也可以使用适当的os.chdir()命令开始python程序。

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

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