File size: 1,632 Bytes
f465388
 
3df0e86
 
 
6b314b0
3df0e86
 
 
 
6b314b0
3df0e86
 
6a646db
3df0e86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import subprocess
import os
import socket
from datetime import datetime
import gradio as gr

# Function to check if a port is in use
def is_port_in_use(port):
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        return sock.connect_ex(('localhost', port)) == 0

# Log file path
log_file_path = 'log.txt'

# Log the startup time
with open(log_file_path, 'a') as log_file:
    log_file.write(f"\n[{datetime.now()}] Script started.\n")

# Port number to check
port_to_check = 7860

# Check if the port is already in use
if is_port_in_use(port_to_check):
    print("API service already running, enjoy!")
    with open(log_file_path, 'a') as log_file:
        log_file.write(f"[{datetime.now()}] API service already running on port {port_to_check}, exiting script.\n")
else:
    # Define the command to run
    command = ['node', 'api.js']
    
    # Log the startup information
    with open(log_file_path, 'a') as log_file:
        log_file.write(f"[{datetime.now()}] No service found on port {port_to_check}. Starting API service...\n")
    
    # Open the log file for writing the process output
    with open(log_file_path, 'a') as log_file:
        # Spawn the node process if the port is not in use
        process = subprocess.Popen(command, stdout=log_file, stderr=subprocess.STDOUT, 
                                   stdin=subprocess.DEVNULL, close_fds=True, 
                                   start_new_session=True)

    # Log the process spawn success
    with open(log_file_path, 'a') as log_file:
        log_file.write(f"[{datetime.now()}] API service started and running in the background.\n")