我如何在Python中命名一个外部命令,就好像我把它写在一个<unk>或命令中?
当前回答
查看Python图书馆的“快速”图书馆,也。
它允许对外程序 / 命令的互动控制,甚至 ssh, ftp, telnet 等。
child = pexpect.spawn('ftp 192.168.0.24')
child.expect('(?i)name .*: ')
child.sendline('anonymous')
child.expect('(?i)password')
其他回答
最多案例:
在大多数情况下,一个短片的代码,如此,是你将需要的一切:
import subprocess
import shlex
source = "test.txt"
destination = "test_copy.txt"
base = "cp {source} {destination}'"
cmd = base.format(source=source, destination=destination)
subprocess.check_call(shlex.split(cmd))
它是干净和简单的。
subprocess.check_call 以论点运行命令,等待命令完成。 shlex.split 使用 shell-like syntax 分割行 cmd
其他案例:
如果这不适用于某些特定的命令,最有可能你有一个问题与命令线的解释器. 操作系统选择了默认一个不适合你的程序类型或可能没有找到适当的一个在系统可执行的路径。
例子:
使用Unix系统上的转向操作器
input_1 = "input_1.txt"
input_2 = "input_2.txt"
output = "merged.txt"
base_command = "/bin/bash -c 'cat {input} >> {output}'"
base_command.format(input_1, output=output)
subprocess.check_call(shlex.split(base_command))
base_command.format(input_2, output=output)
subprocess.check_call(shlex.split(base_command))
正如《Python Zen: Explicit is better than implicit》中所说的那样。
因此,如果使用 Python >=3.6 函数,它会看起来像这样:
import subprocess
import shlex
def run_command(cmd_interpreter: str, command: str) -> None:
base_command = f"{cmd_interpreter} -c '{command}'"
subprocess.check_call(shlex.split(base_command)
最简单的方式运行任何命令,并获得结果:
from commands import getstatusoutput
try:
return getstatusoutput("ls -ltr")
except Exception, e:
return None
下面是我的两个百分点:在我看来,这是处理外部命令时最好的做法......
这些是执行方法的回报值......
pass, stdout, stderr = execute(["ls","-la"],"/home/user/desktop")
这是执行方法......
def execute(cmdArray,workingDir):
stdout = ''
stderr = ''
try:
try:
process = subprocess.Popen(cmdArray,cwd=workingDir, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1)
except OSError:
return [False, '', 'ERROR : command(' + ' '.join(cmdArray) + ') could not get executed!']
for line in iter(process.stdout.readline, b''):
try:
echoLine = line.decode("utf-8")
except:
echoLine = str(line)
stdout += echoLine
for line in iter(process.stderr.readline, b''):
try:
echoLine = line.decode("utf-8")
except:
echoLine = str(line)
stderr += echoLine
except (KeyboardInterrupt,SystemExit) as err:
return [False,'',str(err)]
process.stdout.close()
returnCode = process.wait()
if returnCode != 0 or stderr != '':
return [False, stdout, stderr]
else:
return [True, stdout, stderr]
我总是使用纺织品来做这些事情,这里是一个演示代码:
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)
还有不同的方式来处理返回代码和错误,你可能想打破输出,并提供新的输入(在预期类型的风格)。或者你将需要重新引导标准输入,标准输出和标准错误运行在不同的tty(例如,当使用GNU屏幕)。
因此,这里是我们写的Python模块,可以处理你想要的几乎任何东西,如果没有,它是非常灵活的,所以你可以轻松地扩展它:
它不单独工作,需要一些我们的其他工具,并在过去的几年里获得了很多专门的功能,所以它可能不是一个下降的替代品,但它可以给你很多关于如何运行命令的Python内部工作以及如何处理某些情况的想法。
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从终端/命令行调用VS代码编辑器
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 查看PS命令的全部输出