Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Launch a shell command with in a python script, wait for the termination and return to the script

I've a python script that has to launch a shell command for every file in a dir:

import os  files = os.listdir(".") for f in files:     os.execlp("myscript", "myscript", f) 

This works fine for the first file, but after the "myscript" command has ended, the execution stops and does not come back to the python script.

How can I do? Do I have to fork() before calling os.execlp()?

like image 794
Davide Gualano Avatar asked Nov 28 '08 10:11

Davide Gualano


People also ask

How do I run a shell command in Python?

If you need to execute a shell command with Python, there are two ways. You can either use the subprocess module or the RunShellCommand() function. The first option is easier to run one line of code and then exit, but it isn't as flexible when using arguments or producing text output.

How do I terminate Python shell?

Press CTRL + C to terminate the Python script To stop a script in Python, press Ctrl + C.

How do I run a shell command in Python using subprocess?

Python Subprocess Run Function The subprocess. run() function was added in Python 3.5 and it is recommended to use the run() function to execute the shell commands in the python program. The args argument in the subprocess. run() function takes the shell command and returns an object of CompletedProcess in Python.

How do I keep a Python shell open?

cmd /k is the typical way to open any console application (not only Python) with a console window that will remain after the application closes. The easiest way I can think to do that, is to press Win+R, type cmd /k and then drag&drop the script you want to the Run dialog.


2 Answers

subprocess: The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.

http://docs.python.org/library/subprocess.html

Usage:

import subprocess process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE) process.wait() print process.returncode 
like image 72
user39307 Avatar answered Oct 21 '22 04:10

user39307


You can use subprocess.Popen. There's a few ways to do it:

import subprocess cmd = ['/run/myscript', '--arg', 'value'] p = subprocess.Popen(cmd, stdout=subprocess.PIPE) for line in p.stdout:     print line p.wait() print p.returncode 

Or, if you don't care what the external program actually does:

cmd = ['/run/myscript', '--arg', 'value'] subprocess.Popen(cmd).wait() 
like image 20
Harley Holcombe Avatar answered Oct 21 '22 05:10

Harley Holcombe