argparse, создать как l oop мою командную строку в python? - PullRequest
0 голосов
/ 27 мая 2020

Это код, функции r передается 1 аргумент int.

    import pyautogui as P 
    from colorama import *
    import sys
    import os
    import time
    import argparse

    init(autoreset=True)

    class Automate:

          def classify(self):

              parser = argparse.ArgumentParser(description='test')
              parser.add_argument('-w', '-write', type=str, nargs=1, help='--Ex--')
              parser.add_argument('-s', '-sleep', type=int, nargs=1 , help='--Ex--')
              parser.add_argument('-l', '-local', type=str, nargs=1, help='--Ex--')
              parser.add_argument('-r', '-repeat', type=int, help='--Ex--')

              A = parser.parse_args()

              if A.w:
                 P.typewrite(A.w.replace("_"," "), 0.25)

              elif A.s:
                  time.sleep(A.s[0])

              elif A.l:
                  co = P.locateOnScreen(A.l[0])
                  print(f"{co}")

              elif A.r:
                   pass

    B = Automate()
    B.classify()

Помогите мне заставить команду r повторять команды, которые вы вводите через командную строку (команды будут различаться в зависимости от на то, что хочет пользователь) без создания бесконечного l oop. Спасибо за внимание и помощь.

F:\>python aut.py -write HELLO_WORLD -s 2 -l image.PNG -r 2  #times

F:\>python aut.py -s 2 -w HELLO_WORLD -repeat 3 -l image.PNG  #times

F:\>python aut.py -r 4 -l image.PNG -w HELLO_WORLD -sleep 2  #times

1 Ответ

0 голосов
/ 27 мая 2020

Если вы добавите default=1 для -repeate, вы можете запустить l oop

Используйте if вместо elif, чтобы запустить все функции для аргументов в одной строке.

Но они всегда будут выполняться в порядке write, sleep, local. Чтобы управлять порядком, возможно, вам придется изменить все аргументы. Возможно, это может помочь порядок аргументов argparse

  parser = argparse.ArgumentParser(description='test')
  parser.add_argument('-w', '-write', type=str, nargs=1, help='--Ex--')
  parser.add_argument('-s', '-sleep', type=int, nargs=1 , help='--Ex--')
  parser.add_argument('-l', '-local', type=str, nargs=1, help='--Ex--')
  parser.add_argument('-r', '-repeat', type=int, default=1, help='--Ex--')

  A = parser.parse_args()

  for x in range(A.r):

      if A.w:
         P.typewrite(A.w.replace("_"," "), 0.25)

      if A.s:  # use `if` instead of `elif`
          time.sleep(A.s[0])

      if A.l:  # use `if` instead of `elif`
          co = P.locateOnScreen(A.l[0])
          print(f"{co}")

EDIT:

Вы можете использовать список с аргументами

 parse_args(["-write", "HELLO_WORLD", "-s", "2", "-l", "image.PNG", "-r", "2"])

, чтобы вы могли изменить свой скрипт, чтобы он работал как раньше

  class Automate:
      def classify(self, arguments):

          # ... code ...

          A = parser.parse_args(arguments)

          # ... code ...

  if __name__ == "__main__":
      B = Automate()
      B.classify(sys.argv)

И вы также можете использовать его в другом скрипте

 from aut import Automate

 B = Automate()
 B.classify(["-write", "HELLO_WORLD", "-s", "2", "-l", "image.PNG", "-r", "2"]) 
 B.classify(["-s", "2", "-w", "HELLO_WORLD", "-repeat", "3", "-l", "image.PNG"])
 B.classify(["-r", "4", "-l",  "image.PNG", "-w", "HELLO_WORLD", "-sleep", "2"]) 

или используя split(" "), если вы этого не сделаете t используйте пробелы в аргументах

 from aut import Automate

 B = Automate()
 B.classify("-write HELLO_WORLD -s 2 -l image.PNG -r 2".split(" ")) 
 B.classify("-s 2 -w HELLO_WORLD -repeat 3 -l image.PNG".split(" ")) 
 B.classify("-r 4 -l image.PNG -w HELLO_WORLD -sleep 2".split(" ")) 

Или просто создайте файл .bat с

python aut.py -write HELLO_WORLD -s 2 -l image.PNG -r 2  #times
python aut.py -s 2 -w HELLO_WORLD -repeat 3 -l image.PNG  #times
python aut.py -r 4 -l image.PNG -w HELLO_WORLD -sleep 2  #times
...