p = subprocess.Popen("python 管理员界面.py", stdout=subprocess.PIPE) while True: output = p.stdout.readline() output_str = output.decode("utf-8").strip() print(output_str)如何判断子进程结束后退出循环
时间: 2024-03-17 09:46:17 浏览: 17
你可以使用 `poll()` 方法来判断子进程是否已经结束。当 `poll()` 方法返回非 None 值时,表示子进程已经结束。你可以在循环中使用 `break` 语句来退出循环。下面是一个示例代码:
```
import subprocess
p = subprocess.Popen("python 管理员界面.py", stdout=subprocess.PIPE)
while True:
output = p.stdout.readline()
output_str = output.decode("utf-8").strip()
print(output_str)
if p.poll() is not None:
break
```
在上面的代码中,我们在每次循环中调用 `poll()` 方法来判断子进程是否已经结束,并在子进程结束后使用 `break` 语句退出循环。
相关问题
loadjietu=subprocess.Popen(fullcmd.split(),stdout=subprocess.PIPE) 如何判断有值
可以使用`communicate()`方法获取子进程的标准输出并判断是否有值。示例代码如下:
```
loadjietu = subprocess.Popen(fullcmd.split(),stdout=subprocess.PIPE)
output, error = loadjietu.communicate()
if output:
print("子进程输出有值:",output)
else:
print("子进程输出为空")
```
`communicate()`方法会等待子进程执行完毕并返回标准输出和标准错误。如果标准输出不为空,则代表子进程执行成功并输出了一些信息。如果标准输出为空,则代表子进程执行失败或没有输出信息。注意,`communicate()`方法只能调用一次,因为它会阻塞当前进程等待子进程执行完毕。如果需要多次获取子进程的输出,可以使用`stdout.readline()`或`stdout.readlines()`等方法读取子进程的标准输出流。
import subprocesswhile True: proc = subprocess.Popen(["python3", "/home/pi/Documents/8-17/simplest.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) try: while True: if proc.poll() is not None: break # 读取子进程的输出 output = proc.stdout.readline().decode().strip() if output: print(output) error = proc.stderr.readline().decode().strip() if error: print(error) except KeyboardInterrupt: proc.terminate() break simplest 里面ffpeg推流打印信息没有在终端输出
这个问题可能是因为 `subprocess` 模块的缓冲机制导致的。可以尝试使用 `subprocess.PIPE` 的 `bufsize` 参数来控制缓冲区大小,或者使用 `subprocess.STDOUT` 将标准输出和标准错误输出合并,以便更好地捕捉子进程的输出信息。比如:
```python
import subprocess
while True:
proc = subprocess.Popen(["python3", "/home/pi/Documents/8-17/simplest.py"],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
try:
while True:
if proc.poll() is not None:
break
# 读取子进程的输出
output = proc.stdout.readline().decode().strip()
if output:
print(output)
proc.wait()
except KeyboardInterrupt:
proc.terminate()
break
```
这里将标准错误输出合并到标准输出中,并使用 `proc.wait()` 等待子进程结束。另外,还可以使用 `universal_newlines=True` 参数将字节流转换为文本流,以便更方便地处理输出。