好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Python中的子进程是什么

子进程

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

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

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

#!/usr/bin/env python
# coding=utf-8
import subprocess
print("$ nslookup HdhCmsTestyangcongchufang测试数据")
r = subprocess.call(['nslookup', 'HdhCmsTestyangcongchufang测试数据'])
print("Exit code: ", r)

执行结果:

? python subcall.py
$ nslookup HdhCmsTestyangcongchufang测试数据
Server:     219.141.136.10
Address:    219.141.136.10#53
Non-authoritative answer:
Name:   HdhCmsTestyangcongchufang测试数据
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测试数据municate(b"set q=mx\nyangcongchufang测试数据\nexit\n")
print(output.decode("utf-8"))
print("Exit code:", p.returncode)

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

set q=mx
yangcongchufang测试数据
exit

相关推荐:

Python中的多进程是什么

查看更多关于Python中的子进程是什么的详细内容...

  阅读:20次