简体   繁体   English

从Notepad ++在IDLE中运行Python时打开外部文件

[英]Opening an external file while running Python in IDLE from Notepad++

I have two files, both on my Desktop: 我的桌面上有两个文件:

sotest.py sotest.py

print 'Hello world'

sotest2.py sotest2.py

foo = open ('sotest.py', 'r')

I'm running Python out of Notepad++ as follows (from Use IDLE to launch script using the full file path ): 我正在Notepad ++之外运行Python,如下所示(从“ 使用IDLE启动使用完整文件路径的脚本” ):

C:\Program Files (x86)\Python27\Lib\idlelib\idle.bat -r "$(FULL_CURRENT_PATH)"

Running sotest2.py returns the following: 运行sotest2.py将返回以下内容:

Traceback (most recent call last):
  File "C:\Users\doncherry\Desktop\sotest2.py", line 7, in <module>
    foo = open ('sotest.py', 'r')
IOError: [Errno 2] No such file or directory: 'sotest.py'

When running the same file out of Pyhton's IDLE, it runs without errors. 在Pyhton的IDLE之外运行同一文件时,该文件运行时不会出错。 If I change sotest2.py to the following, it works out of Notepad++ without problems. 如果我将sotest2.py更改为以下内容,则它可以在Notepad ++之外正常工作。

import sotest

Which part of my configuration do I need to change to make the opening work? 我需要更改配置的哪一部分才能开始工作? I'd prefer to change some setting in Notepad++ rather than adding code to each of my Python files. 我宁愿在Notepad ++中更改一些设置,而不是将代码添加到每个Python文件中。

import sotest works because it searches sotest module in sys.path and the sotest2.py 's directory is added to sys.path if you run sotest2.py as a script. import sotest有效,是因为它在sys.path搜索sotest模块,并且如果您将sotest2.py作为脚本运行,则sotest2.py的目录将添加到sys.path If sotest2.py and sotest.py were in different directories then unless something else put sotest.py 's directory into pythonpath then import sotest inside sotest2.py would fail. 如果sotest2.pysotest.py位于不同的目录中,那么除非将sotest.py的目录放入pythonpath中,否则将sotest.py import sotest sotest2.py将会失败。

To open sotest.py inside sotest2.py as a file you could specify its absolute path. 要将sotest2.py中的sotest.py作为文件打开,可以指定其绝对路径。 Assuming they are in the same directory you could find it automatically: 假设它们在同一目录中,则可以自动找到它:

# in sotest2.py:
import os

scriptdir = os.path.dirname(os.path.abspath(__file__))
path = os.path.join(scriptdir, 'sotest.py')
with open(path) as sotest_file:
     text = sotest_file.read()

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

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