简体   繁体   English

Python:命令行参数与硬编码行的传递方式不同

[英]Python: command line argument not passing the same way as hard coded lines

I'm working on some Selenium scripts to test sites across different devices, browsers, and platforms. 我正在研究一些Selenium脚本来测试不同设备,浏览器和平台上的站点。 I can get the scripts to work using the same code except for two lines where I define command executor URL and the browser capabilities. 我可以使用相同的代码来使用脚本,除了我定义命令执行程序URL和浏览器功能的两行。 I'm trying to get build a single script where I can define these lines using command line arguments. 我正在尝试构建一个脚本,我可以使用命令行参数定义这些行。

Here's my code: 这是我的代码:

from selenium import webdriver
import time
import sys
import getopt
def main(argv):
    #define desired browser capabilities
    desktopCapabilities = {'browserName': 'chrome'} #change browserName to: 'firefox' 'chrome' 'safari' 'internet explorer'
    iosCapabilities = {'platformName': 'iOS' ,'platformVersion': '8.1' ,'deviceName': 'iPad Air','browserName': 'Safari'}
    androidCapabilities = {'chromeOptions': {'androidPackage': 'com.android.chrome'}}
    # Establish the command executor URL
    desktopExecutor = 'http://127.0.0.1:4444/wd/hub'
    iosExecutor = 'http://127.0.0.1:4723/wd/hub'
    androidExecutor = 'http://127.0.0.1:9515'

    cmdExecutor = desktopExecutor
    browserCapabilities = desktopCapabilities
    try:
      opts, args = getopt.getopt(argv,"he:c:",["executor=","capabilities="])
    except getopt.GetoptError:
      print 'test.py -e <executor> -c <capabilities>'
      sys.exit(2)
    for opt, arg in opts:
      if opt == '-h':
         print 'test.py -e <executor> -c <capabilities>'
         sys.exit()
      elif opt in ("-e", "--executor"):
         cmdExecutor = arg
      elif opt in ("-c", "--capabilities"):
         browserCapabilities = arg

    print 'Command executor is:', cmdExecutor
    print 'Desired capabilities are:', browserCapabilities
    driver = webdriver.Remote(command_executor=cmdExecutor, desired_capabilities=browserCapabilities)
    driver.get("http://google.com")
    time.sleep(5)
    driver.quit()
if __name__ == "__main__":
   main(sys.argv[1:])

This code runs as expected if I don't add any arguments via the command line. 如果我不通过命令行添加任何参数,则此代码按预期运行。 It also works if I run it with: 如果我用它运行它也可以工作:

python test.py -e 'http://127.0.0.1:4444/wd/hub'

It breaks if I run it using the following command because -c is not passed as a dictionary: 如果我使用以下命令运行它会中断,因为-c不作为字典传递:

python test.py -e 'http://127.0.0.1:4444/wd/hub' -c {'browserName': 'firefox'}

How can I get this to run this with: 如何通过以下方式运行此操作:

python test.py -e iosExecutor -c iosCapabilities

Here's the output I get when I run the command mentioned above: 这是我运行上述命令时得到的输出:

 python my_script.py -e iosExecutor --capabilities iosCapabilities
Command executor is: iosExecutor
Desired capabilities are: iosCapabilities
Traceback (most recent call last):
  File "my_script.py", line 38, in <module>
    main(sys.argv[1:])
  File "my_script.py", line 33, in main
    driver = webdriver.Remote(command_executor=cmdExecutor, desired_capabilities=browserCapabilities)
  File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 62, in __init__
    raise WebDriverException("Desired Capabilities must be a dictionary")
selenium.common.exceptions.WebDriverException: Message: Desired Capabilities must be a dictionary

Basically it is running as if I passed line 33 like this: 基本上它正在运行,好像我像这样通过第33行:

driver = webdriver.Remote(command_executor="iosExecutor", desired_capabilities="iosCapabilities")

It also works if I hard code lines 15 and 16 with "iosExecutor" and "iosCapabilites" so this tells me it's how I'm passing info from the CLI. 如果我使用“iosExecutor”和“iosCapabilites”硬编码第15行和第16行,它也可以工作,所以这告诉我它是如何从CLI传递信息的。

Any advice would be great. 任何建议都会很棒。 I'm quite new to this (programming) so I'm guessing there may be a better way to do this, but Google hasn't cleared it up for me. 我对这个(编程)很陌生,所以我猜可能有更好的方法来做到这一点,但谷歌还没有为我清理它。

Using argparse would make things much easier. 使用argparse会让事情变得更容易。 For capabilities you can use json.loads , or ast.literal_eval as a type , as, for example, was done here: 对于capabilities您可以使用json.loadsast.literal_eval作为类型 ,例如,在此处完成:

As for executor , either pass a url in as a string, or define a user-friendly mapping, like: 对于executor ,要么将URL作为字符串传递,要么定义用户友好的映射,如:

EXECUTORS = {
    'desktop': 'http://127.0.0.1:4444/wd/hub',
    'ios': 'http://127.0.0.1:4723/wd/hub',
    'android': 'http://127.0.0.1:9515'
}

Here's how the code would look like in the end: 以下是代码最终的样子:

import ast
import time
import argparse

from selenium import webdriver


EXECUTORS = {
    'desktop': 'http://127.0.0.1:4444/wd/hub',
    'ios': 'http://127.0.0.1:4723/wd/hub',
    'android': 'http://127.0.0.1:9515'
}

parser = argparse.ArgumentParser(description='My program.')
parser.add_argument('-c', '--capabilities', type=ast.literal_eval)
parser.add_argument('-e', '--executor', type=str, choices=EXECUTORS)

args = parser.parse_args()

driver = webdriver.Remote(command_executor=EXECUTORS[args.executor], desired_capabilities=args.capabilities)
driver.get("http://google.com")
time.sleep(5)
driver.quit()

Sample script runs: 示例脚本运行:

$ python test.py -e android -c "{'chromeOptions': {'androidPackage': 'com.android.chrome'}}"
$ python test.py -e ios -c "{'platformName': 'iOS' ,'platformVersion': '8.1' ,'deviceName': 'iPad Air','browserName': 'Safari'}" 
$ python test.py -e desktop -c "{'browserName': 'chrome'}"

And, as a bonus, you get a built-in help magically made by argparse : 并且,作为奖励,您将获得由argparse神奇地制作的内置帮助:

$ python test.py --help
usage: test.py [-h] [-c CAPABILITIES] [-e {android,ios,desktop}]

My program.

optional arguments:
  -h, --help            show this help message and exit
  -c CAPABILITIES, --capabilities CAPABILITIES
  -e {android,ios,desktop}, --executor {android,ios,desktop}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM