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
173 views
in Technique[技术] by (71.8m points)

python - Is there any way to condense my code so it does not take up so many lines?

I'm writing my program in python and have it working properly, but it's over 500 lines of code. I think there is a way I can condense my code, but I'm not sure how I should do it

Here's an example of some of my code:

def click():
    if clicked1.get() == "app1":
        os.startfile(r"C:Users
edDesktopapp1")
        i = 0
        while i < 20:
            try:
                app.connect(title_re=".*app1")
                break
            except pywinauto.findwindows.ElementNotFoundError:
                time.sleep(1)
                i += 1
        app1 = app.top_window()
        app1.move_window(x1, y1)
        time.sleep(.5)
        app1.maximize()
    if clicked1.get() == "app2":
        os.startfile(r"C:Program Files (x86)app2")
        i = 0
        while i < 20:
            try:
                app.connect(title_re=".*app2")
                break
            except pywinauto.findwindows.ElementNotFoundError:
                time.sleep(1)
                i += 1
        app1 = app.top_window()
        app1.move_window(x1, y1)
        time.sleep(.5)
        app1.maximize()

I basically have about 20 of those if statements for each different application and for each different clicked (1-4). Is there any way I can shrink my code so it doesn't take up so many lines? Perhaps using variables?

question from:https://stackoverflow.com/questions/65922209/is-there-any-way-to-condense-my-code-so-it-does-not-take-up-so-many-lines

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

1 Reply

0 votes
by (71.8m points)

Here's a data driven approach that lets you add apps to the map at the top of the code, and also makes it easy for you to add additional per-app quantities to each of the map entries:

apps = {
    "app1": {
        "startfile": r"C:Users
edDesktopapp1",
        "title_re": ".*app1"
    },
    "app2": {
        "startfile": r"C:Program Files (x86)app2",
        "title_re": ".*app2"
    }
}

def click():
    if clicked1.get() in apps:
        app = apps[clicked1.get()]
        os.startfile(app["startfile"])
        i = 0
        while i < 20:
            try:
                app.connect(title_re=app["title_re"])
                break
            except pywinauto.findwindows.ElementNotFoundError:
                time.sleep(1)
                i += 1
        app1 = app.top_window()
        app1.move_window(x1, y1)
        time.sleep(.5)
        app1.maximize()

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

...