Reputation: 1024
I am trying to open a .txt
file in Windows. The code is as follows:
subprocess.Popen("C:\folder\file.txt", shell=True)
This works perfectly fine. The default editor is automatically opened and the file is loaded, however, I have read somewhere before that invoking calls through the shell (cmd.exe in Windows) is less safe. How can I do the same without it. Simply setting shell=False
is giving me the error:
OSError: [WinError 193] %1 is not a valid Win32 application
Now, I can try this as a workaround:
subprocess.Popen("notepad C:\folder\file.txt")
but this only works if notepad is available, hence loses its generality.
Upvotes: 2
Views: 505
Reputation: 9240
The feature you try to use is a builtin thing of the windows cmd.exe. Therefore you need to set the shell=True parameter. The cmd.exe knows what to do with the file you hand in.
If you use shell=False, you try to start the file like a programm and hence nothing happens, since .txt files have no exe-header.
Read more about it in the documentation.
Reading further, you can find why using the shell=True parameter can be a security flaw. If you consider to assemble the parameters by user inputs, you should not use this, otherwise nothing speaks against it.
Anyway, I recommend using your second example, because it is explicit. You decide what program to start.
subprocess.Popen("notepad C:\folder\file.txt")
Upvotes: 1
Reputation: 7184
If you are using windows then there is the (non portable) os.startfile
command which will take a file path and open it in the default application for that filetype.
In your case you would do:
import os
os.startfile("C:\folder\file.txt")
Note that this method won't work on Linux and Mac OSX, you'll have to have to use their own utilities for this. (open
for OSX and xdg-open
on Linux) and start them with subprocess.
Upvotes: 2