Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run external executable using Python?

Tags:

I have an external executable file which I am trying to run from a Python script. CMD executable runs but without generating output. Probably it exit before output can be generated. Any suggestion about how to delay exit until outputs are generated?

import subprocess, sys from subprocess import Popen, PIPE exe_str = r"C:/Windows/System32/cmd C:/temp/calc.exe"  parent = subprocess.Popen(exe_str, stderr=subprocess.PIPE) 
like image 548
Ibe Avatar asked Nov 01 '12 12:11

Ibe


People also ask

Can Python create standalone executable?

Underneath the GUI is PyInstaller, a terminal based application to create Python executables for Windows, Mac and Linux. Veteran Pythonistas will be familiar with how PyInstaller works, but with auto-py-to-exe any user can easily create a single Python executable for their system.

Can Python open other programs?

A Python script can start other programs on your computer. For example, it can open up the calculator (to do calculations) or it can open up notepad (so that you can write a document). Or it can open up a sound file that can be played.


2 Answers

use subprocess.call, more info here:

import subprocess subprocess.call(["C:\\temp\\calc.exe"]) 

or

import os os.system('"C:/Windows/System32/notepad.exe"') 

i hope it helps you...

like image 67
Aragon Avatar answered Oct 15 '22 21:10

Aragon


The os.system method is depreciated and should not be used in new applications. The subprocess module is the pythonic way to do what you require.

Here is an example of some code I wrote a few weeks ago using subprocess to load files, the command you need to use to delay exit until data has been received and the launched program completes is wait():

import subprocess  cmd = "c:\\file.exe" process = subprocess.Popen(cmd, stdout=subprocess.PIPE, creationflags=0x08000000) process.wait() 

creationflags=0x08000000 is an optional parameter which suppresses the launch of a window, which can be useful if the program you are calling does not need to be directly seen.

like image 20
sgrieve Avatar answered Oct 15 '22 22:10

sgrieve