Search code examples
pythonwindowsshellpopen

Avoiding shell=True in Popen


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.


Solution

  • 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.