Can I open an application from a script during runtime?

Question:

I was wondering if i could open any kind of application in Python during runtime?

Asked By: Anurag-Sharma

||

Answers:

Assuming that you are using Windows you would use one of the following commands like this.

subprocess.call

import subprocess
subprocess.call('C:\myprogram.exe')

os.startfile

import os
os.startfile('C:\myprogram.exe')
Answered By: eandersson

Use the this code : –

 import subprocess
 subprocess.call('drive:\programe.exe')
Answered By: user2037368

Try this :

import os
import subprocess

command  = r"C:UsersNameDesktopfile_name.exe"
os.system(command)
#subprocess.Popen(command)
Answered By: Rahul Sapparapu

Of course you can. Just import import subprocess and invoke subprocess.call('applicaitonName').

For example you want to open VS Code in Ubuntu:

import subprocess
cmd='code';
subprocess.call(cmd)

This line can be also used to open application, if you need to have more information, e.g. as I want to capture error so I used stderr

subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)

Using system you can also take advantage of open function (especially if you are using mac os/unix environment. Can be useful when you are facing permission issue.

import os

path = "/Applications/Safari.app"
os.system(f"open {path}")
Answered By: Kevin Sabbe

Some extra examples for Windows, Linux and MacOS:

import subprocess

# Generic: open explicitly via executable path
subprocess.call(('/usr/bin/vim', '/etc/hosts'))
subprocess.call(('/System/Applications/TextEdit.app/Contents/MacOS/TextEdit', '/etc/hosts'))

# Linux: open with default app registered for file
subprocess.call(('xdg-open', '/tmp/myfile.html'))

# Windows: open with whatever app is registered for the given extension
subprocess.call(('start', '/tmp/myfile.html'))

# Mac: open with whatever app is registered for the given extension
subprocess.call(('open', '/tmp/myfile.html'))

# Mac: open via MacOS app name
subprocess.call(('open', '-a', 'TextEdit', '/etc/hosts'))

# Mac: open via MacOS app bundle name
subprocess.call(('open', '-b', 'com.apple.TextEdit', '/etc/hosts')) 

If you need to open specifically HTML pages or URLs, then there is the webbrowser module:

import webbrowser

webbrowser.open('file:///tmp/myfile.html')

webbrowser.open('https://yahoo.com')

# force a specific browser
webbrowser.get('firefox').open_new_tab('file:///tmp/myfile.html')
Answered By: ccpizza
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.