在python中调用命令行_如何在Python中调用外部命令?

在python中调用命令行

In order to run an external command within python env, or start up a daemon process, or perhaps invoke a command and capture its output, Python supports several methods for invoking an external command.

为了在python env中运行外部命令 ,或者启动守护进程,或者也许调用命令并捕获其输出, Python支持多种方法来调用外部命令

Choosing the method depends upon the requirement if there is a need to retain the output from the command, or send an input to the command, or have control over its lifecycle.

是否需要保留命令的输出或向命令发送输入或控制其生命周期取决于方法的要求。

子流程 (Subprocess)

Subprocess is the recommended module in python (version 3.5 +) to execute an external command. Using the call method of the subprocess module, an external command can be invoked within the python function.

子进程是python(3.5 +版本)中推荐的模块,用于执行外部命令 。 使用subprocess模块的call方法,可以在python函数内调用外部命令。

Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> import subprocess
>>> subprocess.call(['ls', '-l'])
total 8
drwxr-xr-x 4 XXXXX sw 4096 Oct  1 17:37 python_samples
drwxr-xr-x 5 XXXXX sw 4096 Sep 29 19:53 venv
0
>>>

将输出重定向到文件 (Re-directing the output to the file)

In order to redirect the output to a file, using the with function to open the file and use stdout parameter.

为了将输出重定向到文件,请使用with函数打开文件并使用stdout参数。

Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> import subprocess
>>> with open('output.txt', 'w') as f:
...     subprocess.call(['whoami'], stdout=f)
...
>>> exit()
-bash-4.2$ more output.txt
User

将参数作为输入从stdin传递到命令 (Passing an argument as input from stdin to command)

Using the call() . Open a file and pass the handle using the stdin parameter.

使用call() 。 打开文件并使用stdin参数传递句柄。

-bash-4.2$ python3
Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> import subprocess
>>> with open('output.txt', 'r') as f:
...     subprocess.call(['more'], stdin =f)
...
user
>>>

使用shell = True,可以将shell命令传递给call()函数。 (Using shell=True , a shell command can be passed to the call() function. )

-bash-4.2$ python3
Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> import subprocess
>>> subprocess.call('ls -la', shell=True)
total 20
drwxr-xr-x 4 sradhakr sw 4096 Oct 17 15:42 .
drwxr-xr-x 8 sradhakr sw 8192 Oct  8 13:40 ..
-rw-r--r-- 1 sradhakr sw    9 Oct 17 15:42 output.txt
drwxr-xr-x 4 sradhakr sw 4096 Oct  1 17:37 python_samples
drwxr-xr-x 5 sradhakr sw 4096 Sep 29 19:53 venv
>>>

Using shell=True, comes with a security risk if the command comes from an untrusted source. For example, using the user input, if we receive a command such as rm –rf/ is potentially a dangerous command for a file system.

如果命令来自不受信任的来源,则使用shell = True会带来安全风险。 例如,使用用户输入,如果我们收到诸如rm –rf /之类的命令,则对于文件系统可能是危险的命令。

In order to capture the command output in a string, use subprocess.check_output(),

为了捕获字符串中的命令输出,请使用subprocess.check_output()

import subprocess

try:
    output = subprocess.check_output(input('enter command >> '), shell=True)
    print(output)
except subprocess.CalledProcessError as e:
    print('exception with returncode: {}, command: {}, output = {}'.format(e.returncode, e.cmd, e.output))

Output

输出量

enter command >> whoami
b'user\n'

从命令退出代码 (Exit code from the command)

The exit command determines the success or failure of the processing of the command. The return value of the call() is the exit code and it determines the result of the processing of the command.

exit命令确定命令处理的成功或失败。 call()的返回值是退出代码,它确定命令处理的结果。

Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> import subprocess
>>> print("return code {}".format(subprocess.call('ls -la', shell=True)))
total 20
drwxr-xr-x 4 sradhakr sw 4096 Oct 17 15:42 .
drwxr-xr-x 8 sradhakr sw 8192 Oct  8 13:40 ..
-rw-r--r-- 1 sradhakr sw    9 Oct 17 15:42 output.txt
drwxr-xr-x 4 sradhakr sw 4096 Oct  1 17:37 python_samples
drwxr-xr-x 5 sradhakr sw 4096 Sep 29 19:53 venv
return code 0

In order to get additional information about the processing of the external command there is an additional method called subprocess.check_call().

为了获得有关外部命令处理的附加信息,还有一个名为subprocess.check_call()的附加方法。

import subprocess
try:
    print(subprocess.check_call(['cat','random.txt']))
except subprocess.CalledProcessError as e:
     print('exception: returncode: {}, command: {}'.format(e.returncode, e.cmd))

Output

输出量

cat: random.txt: No such file or directory
exception: returncode: 1, command: ['cat', 'random.txt']


翻译自: https://www.includehelp.com/python/how-to-call-an-external-command.aspx

在python中调用命令行

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值