我如何在Python中命名一个外部命令,就好像我把它写在一个<unk>或命令中?
当前回答
这就是我如何运行我的命令. 这个代码有你需要的一切
from subprocess import Popen, PIPE
cmd = "ls -l ~/"
p = Popen(cmd , shell=True, stdout=PIPE, stderr=PIPE)
out, err = p.communicate()
print "Return code: ", p.returncode
print out.rstrip(), err.rstrip()
其他回答
我总是使用纺织品来做这些事情,这里是一个演示代码:
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 subprocess
p = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in p.stdout.readlines():
print line,
retval = p.wait()
事实上,你可以简单地忽略这些参数(stdout=和stderr=)并将像os.system()一样行事。
您可以使用 Popen 从子过程模块运行任何命令。
from subprocess import Popen
首先,一个命令对象是创建的,所有你想要运行的论点。 例如,在下面的剪辑中,指令对象是由所有论点组成的:
cmd = (
"gunicorn "
"-c gunicorn_conf.py "
"-w {workers} "
"--timeout {timeout} "
"-b {address}:{port} "
"--limit-request-line 0 "
"--limit-request-field_size 0 "
"--log-level debug "
"--max-requests {max_requests} "
"manage:app").format(**locals())
然后这个命令对象与Popen一起使用,以启动一个过程:
process = Popen(cmd, shell=True)
这个过程也可以根据任何信号结束,使用下面的代码线:
Popen.terminate(process)
你可以等到完成上述命令的执行:
process.wait()
使用:
import os
cmd = 'ls -al'
os.system(cmd)
os - 此模块提供一个可携带的方式来使用操作系统依赖的功能。
对于更多的 OS 功能,这里是文档。
最简单的方式运行任何命令,并获得结果:
from commands import getstatusoutput
try:
return getstatusoutput("ls -ltr")
except Exception, e:
return None
推荐文章
- django导入错误-没有core.management模块
- 在芹菜中检索队列中的任务列表
- 使用beautifulsoup提取属性值
- 如何禁用标准错误流的日志记录?
- 用Matplotlib在Python中绘制时间
- 类中的Python装饰器
- 在Python中锁定文件
- 得到熊猫栏目的总数
- 从pandas DataFrame中删除名称包含特定字符串的列
- Mock vs MagicMock
- 如何阅读一个。xlsx文件使用熊猫库在iPython?
- 如何访问熊猫组由数据帧按键
- Pandas和NumPy+SciPy在Python中的区别是什么?
- 将列表转换为集合会改变元素的顺序
- 如何在matplotlib更新一个情节