Skip to main content

  | मौसम…

411 समाचार
Public archive edition · Attributed source reporting with original dates · AI drafts are excluded

411 REFERENCE · Wikibooks

Python Programming/External commands

Reference material by Wikibooks contributors. This retains its source identity and is not 411 news reporting.

The traditional way of executing external commands is using os.system(): import os os.system("dir") os.system("echo Hello") exitCode = os.system("echotypo") The modern way, since Python 2.4, is using subprocess module: subprocess.call(["echo", "Hello"]) exitCode = subprocess.call(["dir", "nonexistent"]) The traditional way of executing external commands and reading their output is via popen2 module: import popen2 readStream, writeStream, errorStream = popen2.popen3("dir") # allLines = readStream.readlines() for line in readStream: print(line.rstrip()) readStream.close() writeStream.close() errorStream.close() The modern way, since Python 2.4, is using subprocess module: import subprocess process = subprocess.Popen(["echo","Hello"], stdout=subprocess.PIPE) for line in process.stdout: print(line.rstrip()) Keywords: system commands, shell commands, processes, backtick, pipe. External links 17.1. subprocess — Subprocess management, python.org, since Python 2.4 15.1. os — Miscellaneous operating system interfaces, python.org 17.5. popen2 — Subprocesses with accessible I/O streams, python.org, deprecated since Python 2.6