Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
666 views
in Technique[技术] by (71.8m points)

download - Python script won't start in the background on windows

so i have both these scripts:

import os
import subprocess
import sys

def path():
    osupathcheck = True
    while osupathcheck:
        osupath = input("enter osu path here: ")
        print(os.path.abspath(osupath + '/osu!.exe'))
        try:
            if os.path.isfile(os.path.abspath(osupath + '/osu!.exe')):
                print("Success: folder contain osu.exe")
                with open("path.txt", "w") as f:
                    f.write(osupath)
                osupathcheck = False
            else:
                print("Error: Folder doesn't contain osu.exe")

        except NameError:
            print("Error: Input isn't a path or the specified path is incorrect")

def spawn_program_and_die(program, exit_code=0):
    subprocess.Popen(program)
    sys.exit(exit_code)

if __name__ == "__main__":
    print("Checking modules...")
    try: 
        import browser_cookie3
        import requests
        from bs4 import BeautifulSoup as BS
        print("successfully imported browser_cookie3, requests, bs4 and Flask")
    except ImportError:
        promptm = True
        while promptm:
            i = input("browser_cookie3, requests and bs4 are required to download maps from this program, would you like to install these packages? (Require pip) Y/n: ")
            if i == "Y" or i == "y":
                subprocess.call([sys.executable, "-m", "pip", "install", "browser_cookie3"])
                subprocess.call([sys.executable, "-m", "pip", "install", "requests"])
                subprocess.call([sys.executable, "-m", "pip", "install", "bs4"])
                subprocess.call([sys.executable, "-m", "pip", "install", "Flask"])
                print("successfully imported browser_cookie3, requests, bs4 and Flask")
                promptm = False
            if i == "N" or i == "n":
                print("exiting...")
                exit()
    print("checking path")
    if not os.path.exists("./path.txt") or os.path.getsize("path.txt") == 0:
        path()
    spawn_program_and_die(['pythonw', 'AltDownload.py'])

and the server script:

import browser_cookie3
import requests
from bs4 import BeautifulSoup as BS
from flask import Flask, request
import re
import os
import asyncio

async def Download_map(osupath, link):
    cj = browser_cookie3.load()
    print("Downloading", link)
    headers = {"referer": link}
    with requests.get(link) as r:
        t = BS(r.text, 'html.parser').title.text.split("·")[0]
    with requests.get(link+"/download", stream=True, cookies=cj, headers=headers) as r:
        if r.status_code == 200:
            try:
                id = re.sub("[^0-9]", "", link)
                with open(os.path.abspath(osupath+"/Songs/"+id+" "+t+".osz"), "wb") as otp:
                    otp.write(r.content)
            except:
                print("You either aren't connected on osu!'s website or you're limited by the API, in which case you now have to wait 1h and then try again.")

async def Download_prep(link):
    
    print("checking link...")

    with open("path.txt", 'r') as f:
        osupath = f.read()

    if link.split("/",4)[:4] == ['https:', '', 'osu.ppy.sh', 'beatmapsets']:
        print("Downloading map...")
        asyncio.run(Download_map(osupath, link.split("#osu")[0]))

app = Flask(__name__)

@app.route('/')
def index():
    asyncio.run(Download_prep(request.args.get('data')))
    return "OK"

app.run(port=5000)

for some reason when i try to run it in background, either by executing it using pythonw, or renaming the file .pyw or using subprocesses, and one more way i forgot, it doesn't work, no python process is generated or maybe it close instantly for a reason i don't know about. Executing the script normally with python and os.system() work as intended and actually run the script. What could i use to make this server script work in the background?

question from:https://stackoverflow.com/questions/65874922/python-script-wont-start-in-the-background-on-windows

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...