我如何在Python中命名一个外部命令,就好像我把它写在一个<unk>或命令中?
当前回答
一个简单的方式是使用OS模块:
import os
os.system('ls')
否则,您还可以使用子过程模块:
import subprocess
subprocess.check_call('ls')
如果您希望结果存储在变量中,请尝试:
import subprocess
r = subprocess.check_output('ls')
其他回答
下面是一个Python脚本,它将在Ubuntu上运行命令,同时在实时显示日志:
command = 'your command here'
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while True:
output = process.stdout.readline().decode()
if output == '' and process.poll() is not None:
break
if output:
print(output.strip())
rc = process.poll()
if rc == 0:
print("Command succeeded.")
else:
print("Command failed.")
我总是使用纺织品来做这些事情,这里是一个演示代码:
from fabric.operations import local
result = local('ls', capture=True)
print "Content:/n%s" % (result, )
但这似乎是一个很好的工具:sh(Python子处理界面)。
看看一个例子:
from sh import vgdisplay
print vgdisplay()
print vgdisplay('-v')
print vgdisplay(v=True)
使用副过程。
或者一个非常简单的命令:
import os
os.system('cat testfile')
我为此写了一本图书馆,shell.py。
它基本上是现在的旋转器和旋转器,它还支持旋转命令,所以你可以在Python中更容易进行连锁命令,所以你可以做这样的事情:
ex('echo hello shell.py') | "awk '{print $2}'"
对于 Python 3.5+ 而言,建议您从子过程模块中使用运行函数,这将返回一个完整的过程对象,您可以轻松地获得输出和返回代码。
from subprocess import PIPE, run
command = ['echo', 'hello']
result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True)
print(result.returncode, result.stdout, result.stderr)
推荐文章
- django导入错误-没有core.management模块
- 在芹菜中检索队列中的任务列表
- 使用beautifulsoup提取属性值
- 如何禁用标准错误流的日志记录?
- 用Matplotlib在Python中绘制时间
- 类中的Python装饰器
- 在Python中锁定文件
- 得到熊猫栏目的总数
- 从pandas DataFrame中删除名称包含特定字符串的列
- Mock vs MagicMock
- 如何阅读一个。xlsx文件使用熊猫库在iPython?
- 如何访问熊猫组由数据帧按键
- Pandas和NumPy+SciPy在Python中的区别是什么?
- 将列表转换为集合会改变元素的顺序
- 如何在matplotlib更新一个情节