简体   繁体   English

检查子进程是否正在执行

[英]Checking if subprocess is executing

I am trying to use subprocess.popen to execute another python script that creates a listening socket. 我正在尝试使用subprocess.popen执行另一个创建侦听套接字的python脚本。 I want to pass it a default number for the port to bind on. 我想通过默认值绑定端口。 I also want to catch if the port is already in use and the bind fails. 我还想捕获端口是否已在使用中并且绑定失败。 If it fails then I want to call subprocess.popen again and pass it another number to try and bind to. 如果失败,那么我想再次调用subprocess.popen并将其传递给另一个数字以尝试绑定。

first.py first.py

import subprocess

p = subprocess.Popen(["python3.7", "test.py", "4444"], shell=False)

#If p is success (bind succeeded) then I want to continue processing code. 
#Else I want to increment the port and try again.

start.py start.py

import socket, sys

HOST = '127.0.0.1'  # Standard loopback interface address (localhost)
PORT = int(sys.argv[1])        # Port to listen on (non-privileged ports are > 1023)

def stuff():
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        try:
            s.bind((HOST, PORT))
        except:
            print("failed to bind")
            return 1
        s.listen()
        print("Listening")
        conn, addr = s.accept()

        with conn:
            print('Connected by', addr)
            while True:
                data = conn.recv(1024)
                if not data:
                    break
                conn.sendall(data)

stuff()

A couple of things: 有两件事:

  • Just returning 1 from a function called won't make your process's exit code 1 . 仅从称为的函数返回1不会使您的进程的退出代码1 Either do sys.exit(stuff()) or just call sys.exit(1) in stuff() . 要么执行sys.exit(stuff())要么在stuff()调用sys.exit(1) stuff()

  • You can wait for a subprocess to succeed or fail with p.wait() , after which you can look at p.returncode . 您可以使用p.wait()等待子p.wait()成功或失败,然后再查看p.returncode

In your case, you'll probably want to do something like 就您而言,您可能想要做类似的事情

import subprocess

p = subprocess.Popen(["python3.7", "test.py", "4444"], shell=False)
try:
    p.wait(2)
except subprocess.TimeoutExpired:
    pass  # it was probably successful and is now listening
else:
    if p.returncode == 1:
        pass  # nope

And, of course, you could do this with just threads instead of subprocesses. 而且,当然,您可以仅使用线程而不是子流程来完成此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM