Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

python - 从Python调用外部命令(Calling an external command from Python)

您如何在Python脚本中调用外部命令(就像我在Unix Shell或Windows命令提示符下键入的一样)?

  ask by freshWoWer translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Look at the subprocess module in the standard library:

(查看标准库中的子流程模块:)

import subprocess
subprocess.run(["ls", "-l"])

The advantage of subprocess vs. system is that it is more flexible (you can get the stdout , stderr , the "real" status code, better error handling, etc...).

(与system相比, subprocess的优势在于它更灵活(您可以获取stdoutstderr ,“真实”状态代码,更好的错误处理等)。)

The official documentation recommends the subprocess module over the alternative os.system() :

(官方文档建议使用替代os.system()subprocess模块:)

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results;

(subprocess模块提供了更强大的功能来生成新流程并检索其结果。)

using that module is preferable to using this function [ os.system() ].

(使用该模块优于使用此功能[ os.system() ]。)

The Replacing Older Functions with the subprocess Module section in the subprocess documentation may have some helpful recipes.

( subprocess文档中的用子流程模块替换较早的功能部分可能有一些有用的方法。)

For versions of Python before 3.5, use call :

(对于3.5之前的Python版本,请使用call :)

import subprocess
subprocess.call(["ls", "-l"])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...