Spaces:
Running
Running
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") | |