while True : with open('/home/pi/Documents/8-17/simplest_output.txt', 'w') as f: proc = subprocess.Popen(["python3", "/home/pi/Documents/8-17/simplest.py"], stdout=f, stderr=f) proc.wait() # 等待子进程执行完毕 if proc.returncode == 0: print("simplest运行正常.....") break 我想在子进程运行中,主进程循环打印子进程运行成功
时间: 2023-12-10 10:39:02 浏览: 12
你可以在子进程执行完毕后,通过检查 `proc.returncode` 的值来判断子进程是否运行成功,然后在主进程中打印相应的信息。以下是修改后的代码示例:
```python
while True:
with open('/home/pi/Documents/8-17/simplest_output.txt', 'w') as f:
proc = subprocess.Popen(["python3", "/home/pi/Documents/8-17/simplest.py"], stdout=f, stderr=f)
proc.wait() # 等待子进程执行完毕
if proc.returncode == 0:
print("simplest运行正常.....")
break
print("子进程运行失败,正在尝试重新运行...")
```
这样,如果子进程运行成功,就会打印出 `simplest运行正常.....` 的信息。如果子进程运行失败,就会打印出 `子进程运行失败,正在尝试重新运行...` 的信息,并重新开始循环运行子进程。
相关问题
while True : with open('/home/pi/Documents/8-17/simplest_output.txt', 'w') as f: proc = subprocess.Popen(["python3", "/home/pi/Documents/8-17/simplest.py"], stdout=f, stderr=f) proc.wait() # 等待子进程执行完毕 if proc.returncode == 0: print("simplest运行正常.....") break 我想让主进程在simplest运行正常时,循环打印 simplest运行正常
你可以将打印语句放在一个 while 循环内,直到子进程返回值为 0 才跳出循环。例如:
```
while True:
with open('/home/pi/Documents/8-17/simplest_output.txt', 'w') as f:
proc = subprocess.Popen(["python3", "/home/pi/Documents/8-17/simplest.py"], stdout=f, stderr=f)
proc.wait() # 等待子进程执行完毕
if proc.returncode == 0:
while True:
print("simplest运行正常.....")
time.sleep(1)
if not os.path.exists('/home/pi/Documents/8-17/simplest_output.txt'):
break
break
```
这里使用了一个内层的 while 循环,在 simplest 运行正常的同时,不断打印运行正常的信息,直到 simplest_output.txt 文件被删除(即子进程执行结束)才跳出内层循环,跳出外层循环。注意最后需要加上 `time.sleep(1)` 延时一秒,否则会一直打印,造成无法正常退出。
import subprocesswhile True: proc = subprocess.Popen(["python3", "/home/pi/Documents/8-17/simplest.py"]) proc.wait() # 等待子进程执行完毕 if proc.returncode == 0: print("simplest运行正常.....") break simplest执行后终端一直打印simplest的输出而不会打印if判断里的输出,子进程simplest是一个不会运行结束的程序
可以使用 `subprocess.Popen` 的 `stdout` 和 `stderr` 参数将子进程的输出重定向到文件中,这样就不会在终端上打印子进程输出了。修改代码如下:
```python
import subprocess
while True:
with open('/home/pi/Documents/8-17/simplest_output.txt', 'w') as f:
proc = subprocess.Popen(["python3", "/home/pi/Documents/8-17/simplest.py"], stdout=f, stderr=f)
proc.wait() # 等待子进程执行完毕
if proc.returncode == 0:
print("simplest运行正常.....")
break
```
这里将子进程的标准输出和标准错误输出都重定向到了同一个文件 `/home/pi/Documents/8-17/simplest_output.txt` 中,如果子进程运行时间过长,可以通过查看该文件来了解子进程的输出情况。