我如何在Python中命名一个外部命令,就好像我把它写在一个<unk>或命令中?


当前回答

在Python 3.5+中使用子过程,以下是我在Linux上做的技巧:

import subprocess

# subprocess.run() returns a completed process object that can be inspected
c = subprocess.run(["ls", "-ltrh"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(c.stdout.decode('utf-8'))

正如文档中提到的那样,PIPE 值是比特序列,为了正确显示它们,应考虑解码。

上述代码的结果是:

total 113M
-rwxr-xr-x  1 farzad farzad  307 Jan 15  2018 vpnscript
-rwxrwxr-x  1 farzad farzad  204 Jan 15  2018 ex
drwxrwxr-x  4 farzad farzad 4.0K Jan 22  2018 scripts
.... # Some other lines

其他回答

Invoke 是一个 Python (2.7 和 3.4+) 任务执行工具和图书馆. 它提供清洁,高级别的 API 运行 Shell 命令:

>>> from invoke import run
>>> cmd = "pip install -r requirements.txt"
>>> result = run(cmd, hide=True, warn=True)
>>> print(result.ok)
True
>>> print(result.stdout.splitlines()[-1])
Successfully installed invocations-0.13.0 pep8-1.5.7 spec-1.3.1

可以是这样简单的:

import os
cmd = "your command"
os.system(cmd)

如果您需要从 Python 笔记本电脑(如 Jupyter、Zeppelin、Databricks 或 Google Cloud Datalab)中拨打一个支票命令,您只能使用! 预定。

例如,

!ls -ilF

苏丹是一个最近为此而设计的包,它提供了管理用户特权和添加有用的错误消息的一些好处。

from sultan.api import Sultan

with Sultan.load(sudo=True, hostname="myserver.com") as sultan:
  sultan.yum("install -y tree").run()

如果您正在写一个 Python shell 脚本,并且在您的系统上安装了 IPython,您可以使用 bang 预定来在 IPython 中运行一个 shell 命令:

!ls
filelist = !ls