स्क्रिप्ट रनिंग विकल्प मेनू

Sep 14 2020

मेरी स्क्रिप्ट "विकल्प" फ़ोल्डर में निहित लिपियों के लिए एक विकल्प मेनू प्रस्तुत करती है। उपयोगकर्ता उन स्क्रिप्ट का चयन करता है जिन्हें वे चलाना चाहते हैं, और "प्रारंभ" में प्रवेश करते हैं। इसके बाद एक विशिष्ट क्रम में लिपियों को शुरू किया जाता है (शामिल नहीं) - लिपियों का क्रम विकल्प मेनू में होता है।

मेरा मानना ​​है कि यह बहुत छोटा, अधिक आकर्षक और पायथोनिक हो सकता है। मैं इसे कैसे सुधार सकता हूँ?

import os
import xml.etree.ElementTree as ET
import sys
import customError
import login

class optionMenu():
    __slot__ = ["options"]
    def __init__(self):
         #creates a dictionary of usable programs and if they are selected or not
        self.options = {k.split(".")[0].lower():False for k in os.listdir("Options") if k.endswith(".exe")}
    def menu(self): #3 when called displays GUI
        print("\n".join(["[x] "+name if bool == True else "[ ] "+name for name,bool in self.options.items()]))
    def select(self,selection):
        if(selection.lower() == "start" and True not in self.options.values()):
            print("Can't Start")
        elif(selection.lower() == "start" and True in self.options.values()):
            print("starting",",".join([name for name,bool in self.options.items() if bool == True]))
            return False
        elif(selection.lower() not in self.options.keys()):
            print("Please make a valid selection")
        elif(self.options[selection.lower()] == False):
            self.options[selection.lower()] = True
        return True
    def main(self):
        self.menu()
        choice = input("Choice: ")
        return self.select(choice)
# End of OptionMenu Class
class scripts():
    __slot__ = ["tree","root","script","version","scriptName","author","contributors","scriptType","executable"]
    def __init__(self,script):
        self.version = script.find('version').text
        self.scriptName = script.find('scriptName').text
        self.author = script.find('author').text
        self.contributors = self.adjustcon([script.find('contributors').text])
        self.scriptType = script.find('scriptType').text
        self.executable = os.path.join("Options",self.scriptName,".exe")
    def adjustcon(self,contributors):
        if(len(contributors) > 1): #20 checks if selected list is greater than 1 element
            return (", ".join(contributors[:-1]) ,"and",contributors[-1]) #21 formats output -> Running: element,..., and element
        elif(contributors[0] == None):
            return None
        else: #22 if only one selection made
            return (", ".join(contributors))
    def getVersion(self):
        return self.version
    def setVersion(self,version):
        self.version = version
    def getName(self):
        return self.scriptName
    def setName(self,name):
        self.scriptName = name
    def getAuthor(self):
        return self.author
    def setAuthor(self,author):
        self.author = author
    def getContributors(self):
        return self.contributors
    def setContributors(self,contributors):
        self.contributors = contributors
    def getType(self):
        return self.scriptType
    def setTypes(self,type):
        self.scriptType = type
    def getExecutable(self):
        return self.executable
    def setExecutable(self,exe):
        self.executable = exe

def getScripts():
    scriptDict = {k.find('scriptName').text:scripts(k) for k in ET.parse("scriptInfo.xml").getroot().findall('script')}
    return scriptDict


def openingScreen(scripts): #19 formatting for to part that appears.
    script = next(value for key,value in scripts.items() if value.scriptType=="optionMenu")
    scriptName = script.scriptName
    welcome = "{0} WELCOME TO {1} {0}".format("-"*48,scriptName)
    credit = welcome+"""\nVersion: {0}\nDeveloped by {1} With help from {2}
{3} DISCLAIMERS {3}\nVerify that all usernames and password entered are valid. If the script needs to be terminated press ctrl+C.
Select all needed programs, multitool will run them in proper order. Once complete the respective notes/logs will be stored in a folder.\n{4}""".format(script.version,script.author,script.contributors
                                                                                                                                                    ,"-"*int((len(welcome)-13)/2),"-"*len(welcome))
    return (credit,scriptName)

if __name__ == "__main__":
    try:
        scripts = getScripts()
        screen,currentScript = openingScreen(scripts = scripts)
        menu = optionMenu()
        deciding = True
        while deciding:
            os.system('cls||clear') # clears cmd for illusion of updating
            print(screen)
            deciding = menu.main()
        # need to add method by which to pass variables.
        lines = open("RunOrderList.txt","r")
        for line in lines:
            print(line)
        login.login()
    except KeyboardInterrupt: # catch exit command ctrl+C
        print("Exiting {0}".format(currentScript))
        input("Press the enter key to continue...")
    except Exception as e: # Catches Unexpected exceptions
        exc_type, exc_obj, exc_tb = sys.exc_info()
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        print(exc_type, fname, exc_tb.tb_lineno)
```

जवाब

1 user985366 Sep 14 2020 at 21:28

कुल मिलाकर टिप्पणी

आपका मुख्य लक्ष्य जितना संभव हो उतना कोड की कुछ पंक्तियों के साथ संभव नहीं होना चाहिए, भले ही आप कर सकते हैं और भले ही पायथन अभिव्यक्ति संभव हो।

सुझाव 0: कोड शैली और प्रारूपण

एक पायथन शैली गाइड पढ़ें ( https://www.python.org/dev/peps/pep-0008/) और शैली को जल्दी से ठीक करने के लिए अपने कोड को एक ऑटोफ़ॉर्मर के माध्यम से चलाएं। फ़ंक्शन परिभाषाओं के बीच कुछ स्थान एक ऐसी चीज है जो पठनीयता में मदद करेगी।

https://www.tutorialspoint.com/online_python_formatter.htm

उपयोग करते समय आपको कोष्ठक की आवश्यकता नहीं है if, यह जावा और कई अन्य भाषाओं में किया गया है, लेकिन पायथन नहीं।

सुझाव 1: पठनीयता और स्थिरता

self.options = {k.split(".")[0].lower():False for k in os.listdir("Options") if k.endswith(".exe")}

इस तरह कोड को पढ़ना मुश्किल है।

अपने कोड को स्टेपवाइज निर्देशों में विभाजित करके शुरू करें ताकि इसे मानव द्वारा पार्स किया जा सके। लाइनों की संख्या के बारे में चिंता मत करो।

self.options = {}

for k in os.listdir("Options"):
    if k.endswith(".exe"):
        filename = k.split(".")[0].lower()
        self.options[filename] = False

सुझाव 2: ब्लोट (?)

def getVersion(self):
        return self.version
    def setVersion(self,version):
        self.version = version
    def getName(self):
        return self.scriptName
    def setName(self,name):
        self.scriptName = name
    def getAuthor(self):
        return self.author

आपको बसने वालों और गेटर्स की जरूरत नहीं है। बस उन्हें हटाएं और सीधे अपने चर तक पहुंचें। ऐसे कार्यक्रम या परिस्थितियां हो सकती हैं जहां यह समझ में आता है कि बसने और पाने वाले हैं, लेकिन यह एक नहीं है।

सुझाव 3: खुद को दोहराएं नहीं

https://dzone.com/articles/software-design-principles-dry-and-kiss

(और अधिक)

यहां से शुरू हो रहा है

def select(self,selection):
    if(selection.lower() == "start" and True not in self.options.values()):
        print("Can't Start")
    elif(selection.lower() == "start" and True in self.options.values()):
        print("starting",",".join([name for name,bool in self.options.items() if bool == True]))
        return False
    elif(selection.lower() not in self.options.keys()):
        print("Please make a valid selection")
    elif(self.options[selection.lower()] == False):
        self.options[selection.lower()] = True
    return True

selection.lower()और self.optionsबहुत उपयोग किया जाता है, चलो उन्हें एक बार बदले बजाय फिर से परिभाषित करें।

def select(self,selection):
    selection = selection.lower()
    opts = self.options
    if(selection == "start" and True not in opts.values()):
        print("Can't Start")
    elif(selection == "start" and True in opts.values()):
        print("starting",",".join([name for name,bool in opts.items() if bool == True]))
        return False
    elif(selection not in opts.keys()):
        print("Please make a valid selection")
    elif(opts[selection] == False):
        opts[selection] = True
    return True

पहले दो चेक बहुत आम हैं और एक साथ हैं, इसलिए हम उन्हें रिफ्लेक्टर कर सकते हैं।

def select(self,selection):
    selection = selection.lower()
    opts = self.options
    if selection == "start":
        if True in opts.values():
            print("starting",",".join([name for name,bool in opts.items() if bool == True]))
            return False
        else:
            print("Can't Start")
            return True
   
    if selection not in opts.keys():
        print("Please make a valid selection")
    elif(opts[selection] == False):
        opts[selection] = True
    return True

इसमें और सुधार किया जा सकता है लेकिन मैं समय से बाहर चल रहा हूं।

boolएक कीवर्ड है। अपने चरों का नाम न रखें bool।

एक संपादक का उपयोग करें जैसे PyCharm या विज़ुअल स्टूडियो कोड या कुछ और जिसमें ऐसी त्रुटियों के लिए वाक्यविन्यास हाइलाइटिंग और चेतावनी है।