我如何在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')
其他回答
下面是如何呼叫外部程序的概述,包括其优点和缺点:
os.system 将命令和论点转移到您的系统的阴道. 这很好,因为您实际上可以以这种方式同时运行多个命令,并设置管道和输入/输出重定向。 例如: os.system(“some_command < input_file♰ another_command > output_file”) 但是,虽然这是方便的,您必须手动处理阴道字符的逃避,如空间,和
副过程模块应该是你所使用的。
最后,请注意,对于你通过的所有方法,最终命令将由丝带执行,你负责逃避它。 有严重的安全影响,如果你通过的丝带的任何部分不能完全信任。 例如,如果用户进入某些 / 任何部分的丝带. 如果你不确定,只使用这些方法的连续。
print subprocess.Popen("echo %s " % user_input, stdout=PIPE).stdout.read()
想象一下,用户输入了一些“我的妈妈不喜欢我&rm -rf /”可以删除整个文件系统。
有很多方法可以命令。
例如:
如果 and.exe 需要 2 个参数. 在 cmd 我们可以呼叫 sample.exe 使用此: and.exe 2 3 并在屏幕上显示 5。
如果我们使用 Python 脚本来呼叫 and.exe,我们应该这样做。
os.system(cmd,...) os.system(("and.exe" + "" + "2" + " + "3") os.popen(cmd,...) os.popen(("and.exe" + " + "2" + " + "3")) subprocess.Popen(cmd,...) subprocess.Popen(("and.exe" + " + "2" + " + "3"))
它太硬了,所以我们可以与一个空间加入CMD:
import os
cmd = " ".join(exename,parameters)
os.popen(cmd)
使用副过程。
或者一个非常简单的命令:
import os
os.system('cat testfile')
TL;DR 2021年
import subprocess
subprocess.run("ls -a", shell=True)
注意:这是对你的问题的准确答案 - 执行命令
就像在沙子里
偏好之路
如果可能的话,移除箭头顶部并直接运行命令(需要列表)。
import subprocess
subprocess.run(["help"])
subprocess.run(["ls", "-a"])
检查输出
下列代码本身就是:
import subprocess
result = subprocess.run(["ls", "-a"], capture_output=True, text=True)
if "stackoverflow-logo.png" in result.stdout:
print("You're a fan!")
else:
print("You're not a fan?")
查看返回代码
if result.returncode == 127: print("The program failed for some weird reason")
elif result.returncode == 0: print("The program succeeded")
else: print("The program failed unexpectedly")
result.check_returncode()
result = subprocess.run(..., check=True)
result = subprocess.run(..., stderr=subprocess.STDOUT)
使用shell=False 与论点字符串
import subprocess
import shlex
subprocess.run(shlex.split("ls -a"))
常见问题
FileNotFoundError: [Errno 2] 没有此类文件或目录: 'ls -a': 'ls -a'
此分類上一篇: NoneType [...]
确保您已设置 capture_output=True。
您总是从您的程序中获取比特结果. 如果您想像正常字符串一样使用它,则设置文本=真实。
更新:
subprocess.run 是关于 Python 3.5 的推荐方法,如果您的代码不需要与以前的 Python 版本保持兼容性。
下面是文档的一些例子。
运行一个过程:
>>> subprocess.run(["ls", "-l"]) # Doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)
上一篇: 失败的跑步:
>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
捕获输出:
>>> subprocess.run(["ls", "-l", "/dev/null"], stdout=subprocess.PIPE)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n')
原始答案:
我建议尝试发送,这是一个子过程的插槽,其目的是取代旧的模块和功能。
使用 README 的例子:
>>> r = envoy.run('git config', data='data to pipe in', timeout=2)
>>> r.status_code
129
>>> r.std_out
'usage: git config [options]'
>>> r.std_err
''
周围的管道也:
>>> r = envoy.run('uptime | pbcopy')
>>> r.command
'pbcopy'
>>> r.status_code
0
>>> r.history
[<Response 'uptime'>]
推荐文章
- django导入错误-没有core.management模块
- 在芹菜中检索队列中的任务列表
- 使用beautifulsoup提取属性值
- 如何禁用标准错误流的日志记录?
- 用Matplotlib在Python中绘制时间
- 类中的Python装饰器
- 在Python中锁定文件
- 得到熊猫栏目的总数
- 从pandas DataFrame中删除名称包含特定字符串的列
- Mock vs MagicMock
- 如何阅读一个。xlsx文件使用熊猫库在iPython?
- 如何访问熊猫组由数据帧按键
- Pandas和NumPy+SciPy在Python中的区别是什么?
- 将列表转换为集合会改变元素的顺序
- 如何在matplotlib更新一个情节