Python编程
Completion requirements
执行外部命令的传统方法是使用 os.system()
:
Python
import os
os.system("dir")
os.system("echo Hello")
exitCode = os.system("echotypo")
从 Python 2.4 开始,现代方法是使用 subprocess
模块:
Python
import subprocess
subprocess.call(["echo", "Hello"])
exitCode = subprocess.call(["dir", "nonexistent"])
执行外部命令并读取其输出的传统方法是通过 popen2
模块:
Python
import popen2
readStream, writeStream, errorStream = popen2.popen3("dir")
# allLines = readStream.readlines()
for line in readStream:
print(line.rstrip())
readStream.close()
writeStream.close()
errorStream.close()
从 Python 2.4 开始,现代方法是使用 subprocess
模块:
Python
import subprocess
process = subprocess.Popen(["echo","Hello"], stdout=subprocess.PIPE)
for line in process.stdout:
print(line.rstrip())
关键词:系统命令,shell 命令,进程,反引号,管道。
Last modified: Friday, 31 January 2025, 1:20 AM