Open a Python File in Notepad++ from a Program

落花浮王杯 提交于 2020-08-03 03:08:16

问题


I am trying to replicate IDLE's alt + m command (open a module in the sys path) in Notepad++. I like Notepad++ for editing (rather than IDLE), but this is one feature I cannot find.

When alt+m is pressed, I want it to run a program that asks for a module (that's fairly straightforward, so I can do that). My problem is finding the module and then opening it in Notepad++, not simply running the program. In addition, I want it to open in the same instance (same window) in Notepad++, not a new instance.

I've tried this:

import os
f = r"D:\my_stuff\Google Drive\Modules\nums.py"
os.startfile(f, 'notepad++.exe')

However, I get this error:

Traceback (most recent call last):
  File '_filePath_', line 3, in <module>
    os.startfile(f, 'notepad++.exe')
OSError: [WinError 1155] No application is associated with the specified file for this operation: 'D:\\my_stuff\\Google Drive\\Modules\\nums.py'

How can I fix this?

Also, given a string, such as 'nums.py', how can I find the full path of it? It's going to be in one of two folders: 'D:\\my_stuff\\Google Drive\\Modules' or 'C:\\Python27\Lib' (it could also be in various subfolders in the 'Lib' folder). Alternatively, I could simply do:

try:
    fullPath = r'D:\\my_stuff\\Google Drive\\Modules\\' + f
    # method of opening file in Notepad++
except (IOError, FileNotFoundError):
    fullPath = r'C:\\Python27\\Lib\\' + f
    # open in Notepad++

This doesn't account for subfolders and seems rather clunky. Thanks!


回答1:


If your .py files will be associated w/ notepad++ the os.startfile(f, 'notepad++.exe') will work for you (see ftype).

Unless, you would like to create this association , the following code will open notepad ++ for you:

import subprocess
subprocess.call([r"c:\Program ...Notepad++.exe", r"D:\my_stuff\Google Drive\Modules\nums.py"])

Reference: subprocess.call()



来源:https://stackoverflow.com/questions/15450733/open-a-python-file-in-notepad-from-a-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!