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()
?
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.
Press CTRL + C to terminate the Python script To stop a script in Python, press Ctrl + C.
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.
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.
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
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With