Python 如何使函数接受运行时参数
我想定义一个函数,使它能够接受命令行参数 下面是我的代码Python 如何使函数接受运行时参数,python,Python,我想定义一个函数,使它能够接受命令行参数 下面是我的代码 def tc1(resloc): from uiautomator import Device; 'Do some activity' with open(resloc, 'a') as text_file: text_file.write('TC1 PASSED \n') text_file.close() else: with open(r
def tc1(resloc):
from uiautomator import Device;
'Do some activity'
with open(resloc, 'a') as text_file:
text_file.write('TC1 PASSED \n')
text_file.close()
else:
with open(resloc, 'a') as text_file:
text_file.write('TC1 FAILED \n')
text_file.close()
if __name__ == '__main__':
tc1("C:\\<pathtoautomation>\\Results\results.txt")
def tc1(resloc):
从uiautomator导入设备;
“做一些活动”
打开(resloc,'a')作为文本文件:
text\u file.write('TC1已通过\n')
text_file.close()
其他:
打开(resloc,'a')作为文本文件:
text\u file.write('TC1失败\n')
text_file.close()
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
tc1(“C:\\\Results\Results.txt”)
现在,当我从Python执行相同的使用命令行时,它继续引用这里提到的路径<代码> TC1(“C:\\RealthRealsRESULT.TXT”),并且不考虑从命令行
在运行时传递的内容。\Scripts>python.exe trail.py C:\\<pathtoautomationresults>\\Results\results.txt
\Scripts>python.exe trail.py C:\\\\Results\Results.txt
您正在寻找的是
传递给Python脚本的命令行参数列表。argv[0]
脚本名称(这取决于操作系统是否为
完整路径名或不完整)。如果命令是使用-c执行的
解释器的命令行选项,argv[0]设置为字符串
“-c”。如果没有向Python解释器传递脚本名称,则为argv[0]
是空字符串
在标准输入或
命令行,请参阅fileinput模块
您使用它的方式如下:
import sys
def main(argv):
# do something with argv.
if __name__ == "__main__":
main(sys.argv[1:]) # the argv[0] is the current filename.
并称之为使用
python yourfile.py yourgsgohere
查看更详细的用法。您需要使用来获取命令行参数
在您的代码中,它可能如下所示:
import sys
... # other stuff
if __name__ == '__main__':
tc1(sys.argv[1])
有许多方法可以帮助您使用sys.argv使用sys.argv访问命令行参数。以下链接提供了正确用法的详细说明: 您看过了吗?可能是您想要的
tc1(sys.argv[1])
的副本,或者可能是sys.argv[1://code>的循环。