Jump to content

Python Programming/External commands

From Wikibooks, open books for an open world

The traditional way of executing external commands is using os.system():

importosos.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:

importpopen2readStream,writeStream,errorStream=popen2.popen3("dir")# allLines = readStream.readlines()forlineinreadStream:print(line.rstrip())readStream.close()writeStream.close()errorStream.close()

The modern way, since Python 2.4, is using subprocess module:

importsubprocessprocess=subprocess.Popen(["echo","Hello"],stdout=subprocess.PIPE)forlineinprocess.stdout:print(line.rstrip())

Keywords: system commands, shell commands, processes, backtick, pipe.

[edit | edit source]
close