这是代码,函数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命令,以重复您通过命令行输入的命令(命令将根据用户的需要而有所不同)而不会产生无限循环。感谢您的关注和帮助。
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
如果将default=1
添加为-repeate
,则可以运行循环
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)
elif A.s:
time.sleep(A.s[0])
elif A.l:
co = P.locateOnScreen(A.l[0])
print(f"{co}")
编辑:
您可以使用带有参数的胜出列表
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(" ")
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