Anurag-Sharma
Anurag-Sharma

Reputation: 4398

Can I open an application from a script during runtime?

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

Upvotes: 9

Views: 99363

Answers (7)

ccpizza
ccpizza

Reputation: 31676

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')

Upvotes: 0

Kevin Sabbe
Kevin Sabbe

Reputation: 1452

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}")

Upvotes: 4

Muhammad Waqas Dilawar
Muhammad Waqas Dilawar

Reputation: 2322

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)

Upvotes: 0

Rahul Sapparapu
Rahul Sapparapu

Reputation: 59

Try this :

import os
import subprocess

command  = r"C:\Users\Name\Desktop\file_name.exe"
os.system(command)
#subprocess.Popen(command)

Upvotes: -1

user2037368
user2037368

Reputation:

Use the this code : -

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

Upvotes: -1

eandersson
eandersson

Reputation: 26352

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')

Upvotes: 26

Christian Kiewiet
Christian Kiewiet

Reputation: 880

Try having a look at subprocess.call http://docs.python.org/2/library/subprocess.html#using-the-subprocess-module

Upvotes: 1

Related Questions