How to Open a File With the Standard Application

How to open a file with the standard application?

os.startfile is only available for windows for now, but xdg-open will be available on any unix client running X.

if sys.platform == 'linux2':
subprocess.call(["xdg-open", file])
else:
os.startfile(file)

How to open a file with the default associated program

You can use Desktop.getDesktop().open(File file). See the following question for other options: "[Java] How to open user system preffered editor for given file?"

Open document with default OS application in Python, both in Windows and Mac OS

open and start are command-interpreter things for Mac OS/X and Windows respectively, to do this.

To call them from Python, you can either use subprocess module or os.system().

Here are considerations on which package to use:

  1. You can call them via os.system, which works, but...

    Escaping: os.system only works with filenames that don't have any spaces or other shell metacharacters in the pathname (e.g. A:\abc\def\a.txt), or else these need to be escaped. There is shlex.quote for Unix-like systems, but nothing really standard for Windows. Maybe see also python, windows : parsing command lines with shlex

    • MacOS/X: os.system("open " + shlex.quote(filename))
    • Windows: os.system("start " + filename) where properly speaking filename should be escaped, too.
  2. You can also call them via subprocess module, but...

    For Python 2.7 and newer, simply use

    subprocess.check_call(['open', filename])

    In Python 3.5+ you can equivalently use the slightly more complex but also somewhat more versatile

    subprocess.run(['open', filename], check=True)

    If you need to be compatible all the way back to Python 2.4, you can use subprocess.call() and implement your own error checking:

    try:
    retcode = subprocess.call("open " + filename, shell=True)
    if retcode < 0:
    print >>sys.stderr, "Child was terminated by signal", -retcode
    else:
    print >>sys.stderr, "Child returned", retcode
    except OSError, e:
    print >>sys.stderr, "Execution failed:", e

    Now, what are the advantages of using subprocess?

    • Security: In theory, this is more secure, but in fact we're needing to execute a command line one way or the other; in either environment, we need the environment and services to interpret, get paths, and so forth. In neither case are we executing arbitrary text, so it doesn't have an inherent "but you can type 'filename ; rm -rf /'" problem, and if the file name can be corrupted, using subprocess.call gives us little additional protection.
    • Error handling: It doesn't actually give us any more error detection, we're still depending on the retcode in either case; but the behavior to explicitly raise an exception in the case of an error will certainly help you notice if there is a failure (though in some scenarios, a traceback might not at all be more helpful than simply ignoring the error).
    • Spawns a (non-blocking) subprocess: We don't need to wait for the child process, since we're by problem statement starting a separate process.

    To the objection "But subprocess is preferred." However, os.system() is not deprecated, and it's in some sense the simplest tool for this particular job. Conclusion: using os.system() is therefore also a correct answer.

    A marked disadvantage is that the Windows start command requires you to pass in shell=True which negates most of the benefits of using subprocess.

How to open a file in its default program with python

It's hard to be certain from your question as it stands, but I bet your problem is backslashes.

[EDITED to add:] Or actually maybe it's something simpler. Did you put quotes around your pathname at all? If not, that will certainly not work -- but once you do, you will find that then you need the rest of what I've written below.

In a Windows filesystem, the backslash \ is the standard way to separate directories.

In a Python string literal, the backslash \ is used for putting things into the string that would otherwise be difficult to enter. For instance, if you are writing a single-quoted string and you want a single quote in it, you can do this: 'don\'t'. Or if you want a newline character, you can do this: 'First line.\nSecond line.'

So if you take a Windows pathname and plug it into Python like this:

os.startfile('C:\foo\bar\baz')

then the string actually passed to os.startfile will not contain those backslashes; it will contain a form-feed character (from the \f) and two backspace characters (from the \bs), which is not what you want at all.

You can deal with this in three ways.

  • You can use forward slashes instead of backslashes. Although Windows prefers backslashes in its user interface, forward slashes work too, and they don't have special meaning in Python string literals.

  • You can "escape" the backslashes: two backslashes in a row mean an actual backslash. os.startfile('C:\\foo\\bar\\baz')

  • You can use a "raw string literal". Put an r before the opening single or double quotes. This will make backslashes not get interpreted specially. os.startfile(r'C:\foo\bar\baz')

The last is maybe the nicest, except for one annoying quirk: backslash-quote is still special in a raw string literal so that you can still say 'don\'t', which means you can't end a raw string literal with a backslash.

c# open file with default application and parameters

If you want the file to be opened with the default application, I mean without specifying Acrobat or Reader, you can't open the file in the specified page.

On the other hand, if you are Ok with specifying Acrobat or Reader, keep reading:


You can do it without telling the full Acrobat path, like this:

using Process myProcess = new Process();    
myProcess.StartInfo.FileName = "acroRd32.exe"; //not the full application path
myProcess.StartInfo.Arguments = "/A \"page=2=OpenActions\" C:\\example.pdf";
myProcess.Start();

If you don't want the pdf to open with Reader but with Acrobat, chage the second line like this:

myProcess.StartInfo.FileName = "Acrobat.exe";

You can query the registry to identify the default application to open pdf files and then define FileName on your process's StartInfo accordingly.

Follow this question for details on doing that: Finding the default application for opening a particular file type on Windows

Open file with associated application

Just write

System.Diagnostics.Process.Start(@"file path");

example

System.Diagnostics.Process.Start(@"C:\foo.jpg");
System.Diagnostics.Process.Start(@"C:\foo.doc");
System.Diagnostics.Process.Start(@"C:\foo.dxf");
...

And shell will run associated program reading it from the registry, like usual double click does.

How to open file with default application in cmd?

You can use start to open the file with the associated application.


Resources :

  • Open a File in the Default Application using the Windows Command Line (without JDIC) (waybackmachine capture from Oct 30, 2010)

How can you open a file with the program associated with its file extension?

You want to use the file to open as the file argument, not the parameter argument. No need to specify which program to use, ShellExecute will look it up for you.

ShellExecute(0, 0, L"c:\\outfile.txt", 0, 0 , SW_SHOW );

By leaving the verb as NULL (0) rather than L"open", you get the true default action for the file type - usually this is open but not always.

how to open selected files through the default application of the file in VB 2010?

Try this:

now with openfiledialog

Dim OpenFileDlg as new OpenFileDialog.

OpenFileDlg.FileName = "" ' Default file name
OpenFileDlg.DefaultExt = ".xlsx" ' Default file extension
OpenFileDlg.Filter = "Excel Documents (*.XLSX)|*.XLSX"
OpenFileDlg.Multiselect = True
OpenFileDlg.RestoreDirectory = True
' Show open file dialog box
Dim result? As Boolean = OpenFileDlg.ShowDialog()

' Process open file dialog box results
for each path in OpenFileDlg.Filenames
Try
System.Diagnostics.Process.Start(Path)

Catch ex As Exception
MsgBox("Unable to load the file. Maybe it was deleted?")
End Try
If result = True Then
' Open document
Else
Exit Sub
End If
next

This will work if the file is registered with the OS. Use Try catch because it can throw errors if the file is in use.

Edit: It uses always the default application.



Related Topics



Leave a reply



Submit