while True: proc = subprocess.Popen(["python3", "/home/pi/Documents/8-17/simplest.py"]) while proc.poll() is None: time.sleep(1) print("simplest运行中.....") chinanet = isNetChainOK() if chinanet is False: print("网络异常") proc.terminate() break getNet() 怎么既让simplest信息输出到终端,又保存到文件中
时间: 2024-01-21 17:19:22 浏览: 31
你可以使用 `tee` 命令将输出同时保存到终端和文件中。修改你的代码如下所示:
```python
import subprocess
import time
def isNetChainOK():
# 网络连接状态检测代码
pass
def getNet():
# 网络重连代码
pass
while True:
with open('/home/pi/Documents/8-17/simplest.log', 'w') as f:
proc = subprocess.Popen(["python3", "/home/pi/Documents/8-17/simplest.py"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in iter(proc.stdout.readline, b''):
sys.stdout.write(line.decode(sys.stdout.encoding))
f.write(line.decode(sys.stdout.encoding))
proc.communicate()
print("simplest运行中.....")
chinanet = isNetChainOK()
if chinanet is False:
print("网络异常")
break
getNet()
```
这里将 `subprocess.Popen` 的输出重定向到了管道中,并使用 `iter` 函数读取管道中的输出,同时将输出分别写入终端和文件中。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)