请求协助配置Sublime以运行Selenium WebDriver+Python+Pytest测试
Hey there! Let’s get your Selenium WebDriver + Pytest setup running smoothly in Sublime Text. That >>> output you’re seeing means Sublime is launching a Python REPL (interactive shell) instead of executing your test suite—super frustrating, but easy to fix. Here’s a step-by-step guide:
First, make sure you have Package Control installed (if you don’t, go to Tools > Install Package Control and follow the prompts). Then install these key packages via Ctrl+Shift+P > Install Package:
- Pytest: Adds native integration for running pytest tests directly in Sublime.
- Python Improved: Optional but recommended, it boosts Python syntax highlighting and linting for test files.
The default Python build system in Sublime isn’t tailored for pytest. Let’s build a dedicated one:
- Go to
Tools > Build System > New Build System - Replace the default JSON with this configuration:
{ "cmd": ["python", "-m", "pytest", "$file", "-v"], "file_regex": "^\\s*File \"(...*?)\", line ([0-9]+)", "selector": "source.python", "env": {"PYTHONPATH": "${project_path}:${PYTHONPATH}"}, "working_dir": "${project_path}", "shell": true }
- Save it as
Pytest.sublime-build(ensure it’s saved in the default Packages/User directory).
What each part does:
"cmd": ["python", "-m", "pytest", "$file", "-v"]: Runs pytest on your current test file with verbose output to see detailed results."env": {"PYTHONPATH": "${project_path}:${PYTHONPATH}"}: Makes sure Sublime recognizes your project’s dependencies and local modules."working_dir": "${project_path}": Sets your project root as the working directory, so pytest can find all test files correctly.
Before running tests in Sublime, double-check your setup outside the editor first:
- Confirm pytest and Selenium are installed in your active Python environment:
pip install pytest selenium - Verify your browser driver (e.g., ChromeDriver, GeckoDriver) is either:
- Added to your system PATH, or
- Explicitly referenced in your test code (e.g.,
webdriver.Chrome(executable_path="/path/to/chromedriver")).
- Open your test file (make sure it follows pytest conventions: filename starts with
test_, test functions start withtest_—liketest_homepage_load.pywithdef test_homepage_title():). - Go to
Tools > Build Systemand select Pytest (the custom build system you created). - Press
Ctrl+B(Windows/Linux) orCmd+B(Mac) to run the tests.
Troubleshooting Common Issues
- If you still don’t see output or the browser doesn’t launch:
- Check for syntax errors in your test file (Sublime highlights these in red).
- Run the test directly from your terminal first:
pytest test_your_file.py -v—if this works, the issue is with Sublime’s build system, not your test code. - If using a virtual environment, update the
cmdin the build system to point to your venv’s Python path (e.g.,"cmd": ["/path/to/venv/bin/python", "-m", "pytest", "$file", "-v"]).
内容的提问来源于stack exchange,提问作者Ihor Harmatii

