Python中的子进程是什么

子进程

很多时候,子进程并不是自身,而是一个外部进程。我们创建了子进程后,还需要控制子进程的输入和输出。当试图通过python做一些运维工作的时候,subprocess简直是顶梁柱。

subprocess模块可以让我们非常方便地启动一个子进程,然后控制其输入和输出。

下面的例子演示了如何在Python代码中运行命令nslookup <某个域名>,这和命令行直接运行的效果是一样的:

#!/usr/bin/env python
# coding=utf-8
import subprocess
print("$ nslookup www.yangcongchufang.com")
r = subprocess.call(['nslookup', 'www.yangcongchufang.com'])
print("Exit code: ", r)

执行结果:

➜ python subcall.py
$ nslookup www.yangcongchufang.com
Server:     219.141.136.10
Address:    219.141.136.10#53
Non-authoritative answer:
Name:   www.yangcongchufang.com
Address: 103.245.222.133
('Exit code: ', 0)

相关推荐:《Python相关教程》

如果子进程还需要输入,则可以通过communicate()方法输入:

#!/usr/bin/env python
# coding=utf-8
import subprocess
print("$ nslookup")
p = subprocess.Popen(['nslookup'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, err = p.communicate(b"set q=mx
yangcongchufang.com
exit
")
print(output.decode("utf-8"))
print("Exit code:", p.returncode)

上面的代码相当于在命令行执行命令nslookup,然后手动输入:

set q=mx
yangcongchufang.com
exit

相关推荐:

Python中的多进程是什么

来源:PY学习网:原文地址:https://www.py.cn/article.html

hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » Python中的子进程是什么