使用os.system调用Python脚本时如何向被调脚本传递参数
跨脚本传参实现方案
你现有代码的问题很明确:一是不知道怎么给os.system()调用的脚本传参,二是sec_handler.py本身没写接参逻辑,还有几个语法bug顺手给你修了,给两种可直接跑的方案:
方案1:最小改动,命令行传参
不用换调用方式,os.system()本来就支持给被调用脚本传参,只要把参数拼到命令字符串后面就行,改两个地方:
改script1.py的调用逻辑
把ping函数里原来的os.system调用换掉,注意用当前Python解释器路径启动脚本,避免Windows上py文件关联出错,同时把启动sec_handler的逻辑移到driver.get()前面,不然等弹窗弹出来再启动脚本会错过时机:
# 顶部加sys导入 import sys def ping(): sec_handler_path = "C:/Users/val/Documents/code/rmscheck/sec_handler.py" # 参数用引号包裹,避免用户名密码里有空格、特殊字符导致解析错误 os.system(f'"{sys.executable}" "{sec_handler_path}" "{username}" "{password}"') driver = webdriver.Firefox() driver.get(html_file.as_uri()) time.sleep(10) button = driver.find_element_by_name("repingButton") print(button) print(f"Ping {x} successful") driver.close()
改sec_handler.py的接参逻辑
你原来的脚本硬编码了账号密码,还写了个死循环完全没必要,加命令行参数读取,顺便修正autoit.send的语法错误(按键常量要写在字符串里,不是传字典):
import autoit import time import sys def login(username, password): autoit.win_wait("Windows Security", timeout=10) #加超时避免无限死等 autoit.win_activate("Windows Security") time.sleep(0.2) #等窗口完全激活再输入,防止字符丢失 autoit.send(username) autoit.send("{TAB}") autoit.send(password) autoit.send("{ENTER}") if __name__ == "__main__": # sys.argv[0]是脚本自身路径,后面跟的就是传入的参数 if len(sys.argv) >= 3: username = sys.argv[1] password = sys.argv[2] try: login(username, password) except Exception as e: print(f"安全弹窗处理失败: {str(e)}") else: print("参数错误,需要传入用户名和密码")
方案2:整合逻辑(推荐,稳定性更高)
完全没必要单独拆一个sec_handler.py脚本,多进程调度反而容易出时序问题,直接在主脚本里开个守护线程等弹窗就行,不用跨脚本传参,维护更简单:
- 删掉sec_handler.py
- 在script1.py里加线程导入,把弹窗处理逻辑嵌进去:
# 顶部加threading导入 import threading def handle_auth_popup(username, password): try: autoit.win_wait("Windows Security", timeout=15) autoit.win_activate("Windows Security") time.sleep(0.2) autoit.send(username) autoit.send("{TAB}") autoit.send(password) autoit.send("{ENTER}") except Exception as e: print(f"弹窗处理异常: {str(e)}") def ping(): driver = webdriver.Firefox() # 先启动弹窗监听线程,再访问页面,保证不会错过弹窗 auth_thread = threading.Thread( target=handle_auth_popup, args=(username, password), daemon=True ) auth_thread.start() driver.get(html_file.as_uri()) time.sleep(10) button = driver.find_element_by_name("repingButton") print(button) print(f"Ping {x} successful") driver.quit() #比close更彻底,会清理残留的驱动进程
额外优化提示
- 你现在用的
find_element_by_name是Selenium 3的旧API,Selenium 4+已经完全废弃,建议换成标准定位写法:from selenium.webdriver.common.by import By button = driver.find_element(By.NAME, "repingButton") - 固定sleep10秒的写法容错性很差,网络慢的时候会找不到元素,网络快的时候白等,建议换成显式等待,等按钮可点击了再操作。
内容的提问来源于stack exchange,提问作者user2334659
相关产品推荐
相关产品推荐

