我如何在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')
其他回答
如果您需要从 Python 笔记本电脑(如 Jupyter、Zeppelin、Databricks 或 Google Cloud Datalab)中拨打一个支票命令,您只能使用! 预定。
例如,
!ls -ilF
我写了一本小图书馆来帮助这个使用案例:
HTTPS://pypi.org/project/citizenshell/
可以使用安装
pip install citizenshell
然后使用如下:
from citizenshell import sh
assert sh("echo Hello World") == "Hello World"
您可以将标准输出与标准错误分开,并以以下方式提取输出代码:
result = sh(">&2 echo error && echo output && exit 13")
assert result.stdout() == ["output"]
assert result.stderr() == ["error"]
assert result.exit_code() == 13
而且很酷的是,在开始处理输出之前,你不需要等待底层的裂缝出发:
for line in sh("for i in 1 2 3 4; do echo -n 'It is '; date +%H:%M:%S; sleep 1; done", wait=False)
print ">>>", line + "!"
将按行按行按行按行按行按行按行按行按行。
>>> It is 14:24:52!
>>> It is 14:24:53!
>>> It is 14:24:54!
>>> It is 14:24:55!
更多例子可以找到 https://github.com/meuter/citizenshell
在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
您可以尝试使用 os.system() 运行外部命令。
例子:
import os
try:
os.system('ls')
pass
except:
print("Error running command")
pass
在示例中,脚本输入OS并试图运行在OS.system()中列出的命令。如果命令失败,那么它将打印“错误运行命令”而没有脚本因错误而停止。
是的,只是如此简单!
os.popen() 是执行命令的最简单和最安全的方式. 您可以在命令行上执行任何命令. 此外,您还将能够使用 os.popen().read() 捕获命令的输出。
你可以这样做:
import os
output = os.popen('Your Command Here').read()
print (output)
例如,您列出当前目录中的所有文件:
import os
output = os.popen('ls').read()
print (output)
# Outputs list of files in the directory
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用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命令的全部输出