简体   繁体   中英

Notepad++ Python script name 'notepad' is not defined

I have a simple script in Python, in which I am trying to traverse all files in a folder and change them to UTF-8 encoding using Notepad++.

import os;
import sys;
import Npp;
Npp.editor.write('Starting\r\n')
filePathSrc="C:\\SomePath"
Npp.editor.write('FilePath: ' + str(filePathSrc) + '\r\n')
try:
    for root, dirs, files in os.walk(filePathSrc):
        for fn in files:
            if fn[-4:] == '.txt' or fn[-4:] == '.xml' or fn[-5:] == '.html':
                notepad.open(root + "\\" + fn)
                console.write(root + "\\" + fn + "\r\n")
                notepad.runMenuCommand("Encoding", "Encode in UTF-8")
                notepad.save()
                notepad.close()
                Npp.editor.write('Converted ' + str(fn))
except Exception as ex:
    Npp.editor.write('Error occured\r\n')
    Npp.editor.write(str(ex))

However, when I click on Plugins -> Python Script -> Scripts -> MySript, all I get is:

Starting
FilePath: C:\SomePath
Error occured
name 'notepad' is not defined

When searching the Internet, I have never found anyone with the same problem. All similar problems were caused because people were trying to run the script outside of Notepad++. However, I am getting the error when using Notepad++ plugin directly.

As documented here , editor , notepad , and console are all instances defined within the module itself.

You can prefix those objects with Npp. , as you have already done for editor . A less advised option is to do a from Npp import * instead of import Npp .

Do you know the encoding of the source files? If so you can just use Python to convert your files to UTF8 encoding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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