先抛答案:python中的os.system(cmd)是同步的,os.popen(cmd)是异步的。
在linux系统终端执行如下代码,结果如下:
## 在终端执行如下代码: >>> import os >>> def test(): ... print('111') ... os.system('ping 127.0.0.1') ... print('222') ... os.system('ping 127.0.0.1') ... print('333') ... >>> test() 111 PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data. 64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.053 ms 64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.046 ms 64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.050 ms 64 bytes from 127.0.0.1: icmp_seq=4 ttl=64 time=0.048 ms 64 bytes from 127.0.0.1: icmp_seq=5 ttl=64 time=0.054 ms 64 bytes from 127.0.0.1: icmp_seq=6 ttl=64 time=0.052 ms 64 bytes from 127.0.0.1: icmp_seq=7 ttl=64 time=0.050 ms 64 bytes from 127.0.0.1: icmp_seq=8 ttl=64 time=0.054 ms 64 bytes from 127.0.0.1: icmp_seq=9 ttl=64 time=0.056 ms 64 bytes from 127.0.0.1: icmp_seq=10 ttl=64 time=0.048 ms ^C --- 127.0.0.1 ping statistics --- 10 packets transmitted, 10 received, 0% packet loss, time 252ms rtt min/avg/max/mdev = 0.046/0.051/0.056/0.004 ms 222 PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data. 64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.047 ms 64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.053 ms 64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.045 ms 64 bytes from 127.0.0.1: icmp_seq=4 ttl=64 time=0.040 ms 64 bytes from 127.0.0.1: icmp_seq=5 ttl=64 time=0.050 ms 64 bytes from 127.0.0.1: icmp_seq=6 ttl=64 time=0.053 ms 64 bytes from 127.0.0.1: icmp_seq=7 ttl=64 time=0.068 ms ^C --- 127.0.0.1 ping statistics --- 7 packets transmitted, 7 received, 0% packet loss, time 137ms rtt min/avg/max/mdev = 0.040/0.050/0.068/0.012 ms 333
1、只有按Ctrl+C强制终止命令的执行,才会接着执行下一条命令,这说明os.system(cmd)是同步的,本次命令没有执行完,就会阻塞,不会执行下一条命令。
2、os.system()返回值:返回运行命令后系统shell返回的值。其值0表示成功,1表示失败,2表示错误。对于创建子进程失败,system()函数返回-1。
3、os.system()函数在执行过程中进行了以下三步操作:
- 创建一个子进程;
- 在子进程中调用exec函数去执行命令;
- 在父进程中调用wait(阻塞)去等待子进程结束。
4、由于使用该函数经常会莫名其妙地出现错误,但是直接执行命令并没有问题,所以一般建议不要使用。
在linux系统终端执行如下代码,结果如下:
## 在终端执行如下代码: >>> import os >>> import time >>> def test(): ... print('111') ... os.popen('ping 127.0.0.1 > a.txt') ... time.sleep(10) ... print('222') ... os.popen('ping 127.0.0.1 > b.txt') ... print('333') ... return '已退出test()函数' ... >>> test() 111 222 333 '已退出test()函数'
在执行第一个ping 127.0.0.1 > a.txt时,开启一个子进程,主进程继续往下执行,执行到第二个ping 127.0.0.1 > a.txt时,又开启一个子进程,主进程继续往下执行,直到return,开启的两个子进程继续执行。这说明os.popen(cmd)是异步的。
os.popen() 创建一个管道,通过fork一个子进程,然后该子进程执行命令。返回值在标准IO流中,该管道用于父子进程间通信。父进程要么从管道读信息,要么向管道写信息,至于是读还是写取决于父进程调用popen时传递的参数(w或r)。通过popen函数可以读取命令执行过程中的输出。