Open Text File in Notepad++ using Subprocess.Popen

2019-09-01 10:35发布

问题:

I am trying to open a text file in notepad++ using subprocess.Popen

I have tried many variations of the following code, but none of them work:

 subprocess.Popen(['start notepad++.exe', 'C:\Python27\Django_Templates\QC\postits.html'])

 subprocess.Popen(['C:\Program Files (x86)\Notepad++\notepad++.exe', 'C:\Python27\Django_Templates\QC\postits.html'])

There must be a way to do this.

NOTE:

I want to use subprocess.Popen and not os.system because I want to poll to determine whether the program is still open and do something after it closes.

So, this is part of the following code block:

process = subprocess.Popen(.....)
while process.poll() is None:
    sleep(10)
DO SOMETHING AFTER FILE CLOSES

If Popen is not the best way to do this, I am open to any solution that allows me to poll my system (Windows) to determine whether notepad++ is still open, and allows me to do something after it closes.

回答1:

I expect that the problem is that your path separators are backslashes which is the Python string escape character.

Use raw strings instead:

subprocess.Popen([
    r'C:\Program Files (x86)\Notepad++\notepad++.exe', 
    r'C:\Python27\Django_Templates\QC\postits.html'
])

Or escape the backslashes:

subprocess.Popen([
    'C:\\Program Files (x86)\\Notepad++\\notepad++.exe', 
    'C:\\Python27\\Django_Templates\\QC\\postits.html'
])

Or, even better, use os.path.join rather than hard-coded path separators.