Python中的子进程是什么

482次阅读
没有评论

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)

如果子进程还需要输入,则可以通过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\nyangcongchufang.com\nexit\n")
print(output.decode("utf-8"))
print("Exit code:", p.returncode)

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

set q=mx
yangcongchufang.com
exit

相关推荐:

Python中的多进程是什么

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2019-10-21发表,共计1039字。
新手QQ群:570568346,欢迎进群讨论 Python51学习
评论(没有评论)