Home > Enterprise >  I want to run a Python Script on a Server 24/7
I want to run a Python Script on a Server 24/7

Time:03-10

I am making a program that simulates a stock market for a virtual currency. I have not tried anything yet, but I want a Python script to run 24/7 online for a long period of time. The python script should be something like this:

import time
import random

while True:
    number = random.randint(0,5)
    print(number)
    time.sleep(2)

Also, a separate local Python program should be able to retrieve the number variable constantly every 2 seconds. Do I need a web server for this? A physical server? No server? My maximum budget is $100 if possible (I would prefer free). If it helps, I have an old PC I can use as a server if I need to.

I am aware of flask and fastapi, but I do not know how to make a separate Python local program to access the numbers from the online web server. I'm also aware of solutions like AWS and Azure, but I want a more long-term solution that will save me money in the long run.

I have barely any experience in servers and networking, and I couldn't find answers online. Again, I have not tried anything yet.

CodePudding user response:

Sounds fun. Shouldn't cost you anything. The popular serverless options (Azure Functions, AWS Lambda etc.) give you 1M free invocations per month.
If I'm not mistaken, Google's Cloud Function is 2M.

CodePudding user response:

There is a pretty good IDE replit.com where you can run your python but if you want to run it 24/7 you have to get the “hacker” plan which you can get for free with the github education pack if you connect it to your replit account, this pack is also free if you’re in college or high school with a student card. You can work around this by adding a keep alive script to your code. It has pretty fast server that have almost no downtime.

CodePudding user response:

If you really want to just simulate it and there is only one user. You can just return a random number each time the user make a query. It’s irrelevant how often they query it. You can put this up locally or on heroic free plan. But the fact that the user is querying every 2 seconds means lots of requests and so you may exceed the quota.

Import random
from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    return random.randint(0,5)

Say you up it up locally on port 5000. Then, simply going to “localhost:5000” via python or browser will give you that random number.

Let me know if you have more than one user and would like some consistency between the users, e.g. two users querying within 2 seconds will get the same number. I can update the answer.

  • Related