We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Stdout/stderr pipe throws stacktrace if stdout/stderr is mocked by Pytest
I think more an upstream issue (here) instead of for the Pytest plugin.

Stacktrace:

```
pytest project-name/browser_tests --browser chromium --base-url http://localhost:8000/
============================= test session starts ==============================
platform linux -- Python 3.8.5, pytest-6.0.1, py-1.9.0, pluggy-0.13.1
baseurl: http://localhost:8000/
django: settings: config.settings.test (from option)
Using --randomly-seed=1
rootdir: /home/runner/work/project-name/project-name, configfile: setup.cfg
plugins: freezegun-0.4.2, base-url-1.4.2, playwright-0.0.5, cov-2.10.0, sugar-0.9.4, django-3.9.0, randomly-3.4.1, celery-4.4.7, factoryboy-2.0.3, Faker-4.1.1, env-0.6.2
collected 15 items

project-name/browser_tests/test_internal_manager_dashboard.py E [  6%]


==================================== ERRORS ====================================
_ ERROR at setup of test123[chromium] _

launch_browser = <function launch_browser.<locals>.launch at 0x7f6bc73de430>

    @pytest.fixture(scope="session")
    def browser(launch_browser: Callable[[], Browser]) -> Generator[Browser, None, None]:
>       browser = launch_browser()

/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/site-packages/pytest_playwright/pytest_playwright.py:114: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/site-packages/pytest_playwright/pytest_playwright.py:97: in launch
    pw_context = sync_playwright()
/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/site-packages/playwright/__init__.py:27: in sync_playwright
    return SyncPlaywrightContextManager()
/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/site-packages/playwright/main.py:72: in __init__
    self._connection = run_driver()
/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/site-packages/playwright/main.py:67: in run_driver
    return loop.run_until_complete(run_driver_async())
/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/asyncio/base_events.py:616: in run_until_complete
    return future.result()
/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/site-packages/playwright/main.py:48: in run_driver_async
    proc = await asyncio.create_subprocess_exec(
/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/asyncio/subprocess.py:236: in create_subprocess_exec
    transport, protocol = await loop.subprocess_exec(
/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/asyncio/base_events.py:1630: in subprocess_exec
    transport = await self._make_subprocess_transport(
/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/asyncio/unix_events.py:197: in _make_subprocess_transport
    transp = _UnixSubprocessTransport(self, protocol, args, shell,
/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/asyncio/base_subprocess.py:36: in __init__
    self._start(args=args, shell=shell, stdin=stdin, stdout=stdout,
/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/asyncio/unix_events.py:789: in _start
    self._proc = subprocess.Popen(
/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/subprocess.py:804: in __init__
    errread, errwrite) = self._get_handles(stdin, stdout, stderr)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <subprocess.Popen object at 0x7f6bc73dfa60>
stdin = <socket.socket [closed] fd=-1, family=AddressFamily.AF_UNIX, type=SocketKind.SOCK_STREAM, proto=0>
stdout = -1, stderr = <_io.TextIOWrapper encoding='UTF-8'>

    def _get_handles(self, stdin, stdout, stderr):
        """Construct and return tuple with IO objects:
        p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
        """
        p2cread, p2cwrite = -1, -1
        c2pread, c2pwrite = -1, -1
        errread, errwrite = -1, -1
    
        if stdin is None:
            pass
        elif stdin == PIPE:
            p2cread, p2cwrite = os.pipe()
        elif stdin == DEVNULL:
            p2cread = self._get_devnull()
        elif isinstance(stdin, int):
            p2cread = stdin
        else:
            # Assuming file-like object
            p2cread = stdin.fileno()
    
        if stdout is None:
            pass
        elif stdout == PIPE:
            c2pread, c2pwrite = os.pipe()
        elif stdout == DEVNULL:
            c2pwrite = self._get_devnull()
        elif isinstance(stdout, int):
            c2pwrite = stdout
        else:
            # Assuming file-like object
            c2pwrite = stdout.fileno()
    
        if stderr is None:
            pass
        elif stderr == PIPE:
            errread, errwrite = os.pipe()
        elif stderr == STDOUT:
            if c2pwrite != -1:
                errwrite = c2pwrite
            else: # child's stdout is not set, use parent's stdout
                errwrite = sys.__stdout__.fileno()
        elif stderr == DEVNULL:
            errwrite = self._get_devnull()
        elif isinstance(stderr, int):
            errwrite = stderr
        else:
            # Assuming file-like object
>           errwrite = stderr.fileno()
E           io.UnsupportedOperation: fileno

/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/subprocess.py:1504: UnsupportedOperation
---------------------------- Captured stdout setup -----------------------------
kektus <_io.TextIOWrapper encoding='UTF-8'>
=========================== short test summary info ============================
ERROR project-name/browser_tests/test123.py::test123[chromium]
!!!!!!!!!!!!!!!!!!!!!!!!!! stopping after 1 failures !!!!!!!!!!!!!!!!!!!!!!!!!!!
=============================== 1 error in 0.67s ===============================
Makefile:23: recipe for target 'browser_test' failed

```

Using the `-s` parameter is a workaround for that. Issue is persistent since https://github.com/microsoft/playwright-python/pull/145.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `playwright/main.py`
Content:
```
1 # Copyright (c) Microsoft Corporation.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 
15 import asyncio
16 import subprocess
17 import sys
18 from typing import Any
19 
20 from greenlet import greenlet
21 
22 from playwright.async_api import Playwright as AsyncPlaywright
23 from playwright.connection import Connection
24 from playwright.helper import Error
25 from playwright.object_factory import create_remote_object
26 from playwright.path_utils import get_file_dirname
27 from playwright.playwright import Playwright
28 from playwright.sync_api import Playwright as SyncPlaywright
29 from playwright.sync_base import dispatcher_fiber, set_dispatcher_fiber
30 
31 
32 def compute_driver_name() -> str:
33     platform = sys.platform
34     if platform == "darwin":
35         result = "driver-macos"
36     elif platform == "linux":
37         result = "driver-linux"
38     elif platform == "win32":
39         result = "driver-win.exe"
40     return result
41 
42 
43 async def run_driver_async() -> Connection:
44     package_path = get_file_dirname()
45     driver_name = compute_driver_name()
46     driver_executable = package_path / "drivers" / driver_name
47 
48     proc = await asyncio.create_subprocess_exec(
49         str(driver_executable),
50         stdin=asyncio.subprocess.PIPE,
51         stdout=asyncio.subprocess.PIPE,
52         stderr=sys.stderr,
53         limit=32768,
54     )
55     assert proc.stdout
56     assert proc.stdin
57     connection = Connection(
58         proc.stdout, proc.stdin, create_remote_object, asyncio.get_event_loop()
59     )
60     return connection
61 
62 
63 def run_driver() -> Connection:
64     loop = asyncio.get_event_loop()
65     if loop.is_running():
66         raise Error("Can only run one Playwright at a time.")
67     return loop.run_until_complete(run_driver_async())
68 
69 
70 class SyncPlaywrightContextManager:
71     def __init__(self) -> None:
72         self._connection = run_driver()
73         self._playwright: SyncPlaywright
74 
75     def __enter__(self) -> SyncPlaywright:
76         g_self = greenlet.getcurrent()
77 
78         def callback_wrapper(playwright_impl: Playwright) -> None:
79             self._playwright = SyncPlaywright(playwright_impl)
80             g_self.switch()
81 
82         self._connection.call_on_object_with_known_name("Playwright", callback_wrapper)
83         set_dispatcher_fiber(greenlet(lambda: self._connection.run_sync()))
84         dispatcher_fiber().switch()
85         return self._playwright
86 
87     def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
88         self._connection.stop_sync()
89 
90 
91 class AsyncPlaywrightContextManager:
92     def __init__(self) -> None:
93         self._connection: Connection
94 
95     async def __aenter__(self) -> AsyncPlaywright:
96         self._connection = await run_driver_async()
97         self._connection.run_async()
98         return AsyncPlaywright(
99             await self._connection.wait_for_object_with_known_name("Playwright")
100         )
101 
102     async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
103         self._connection.stop_async()
104 
105 
106 if sys.platform == "win32":
107     # Use ProactorEventLoop in 3.7, which is default in 3.8
108     loop = asyncio.ProactorEventLoop()
109     asyncio.set_event_loop(loop)
110 
111 
112 def main() -> None:
113     if "install" not in sys.argv:
114         print('Run "python -m playwright install" to complete installation')
115         return
116     package_path = get_file_dirname()
117     driver_name = compute_driver_name()
118     driver_executable = package_path / "drivers" / driver_name
119     print("Installing the browsers...")
120     subprocess.check_call(f"{driver_executable} install", shell=True)
121 
122     print("Playwright is now ready for use")
123
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/playwright/main.py b/playwright/main.py
--- a/playwright/main.py
+++ b/playwright/main.py
@@ -13,6 +13,7 @@
 # limitations under the License.
 
 import asyncio
+import io
 import subprocess
 import sys
 from typing import Any
@@ -45,11 +46,21 @@
     driver_name = compute_driver_name()
     driver_executable = package_path / "drivers" / driver_name
 
+    # Sourced from: https://github.com/pytest-dev/pytest/blob/49827adcb9256c9c9c06a25729421dcc3c385edc/src/_pytest/faulthandler.py#L73-L80
+    def _get_stderr_fileno() -> int:
+        try:
+            return sys.stderr.fileno()
+        except io.UnsupportedOperation:
+            # pytest-xdist monkeypatches sys.stderr with an object that is not an actual file.
+            # https://docs.python.org/3/library/faulthandler.html#issue-with-file-descriptors
+            # This is potentially dangerous, but the best we can do.
+            return sys.__stderr__.fileno()
+
     proc = await asyncio.create_subprocess_exec(
         str(driver_executable),
         stdin=asyncio.subprocess.PIPE,
         stdout=asyncio.subprocess.PIPE,
-        stderr=sys.stderr,
+        stderr=_get_stderr_fileno(),
         limit=32768,
     )
     assert proc.stdout

{"golden_diff": "diff --git a/playwright/main.py b/playwright/main.py\n--- a/playwright/main.py\n+++ b/playwright/main.py\n@@ -13,6 +13,7 @@\n # limitations under the License.\n \n import asyncio\n+import io\n import subprocess\n import sys\n from typing import Any\n@@ -45,11 +46,21 @@\n     driver_name = compute_driver_name()\n     driver_executable = package_path / \"drivers\" / driver_name\n \n+    # Sourced from: https://github.com/pytest-dev/pytest/blob/49827adcb9256c9c9c06a25729421dcc3c385edc/src/_pytest/faulthandler.py#L73-L80\n+    def _get_stderr_fileno() -> int:\n+        try:\n+            return sys.stderr.fileno()\n+        except io.UnsupportedOperation:\n+            # pytest-xdist monkeypatches sys.stderr with an object that is not an actual file.\n+            # https://docs.python.org/3/library/faulthandler.html#issue-with-file-descriptors\n+            # This is potentially dangerous, but the best we can do.\n+            return sys.__stderr__.fileno()\n+\n     proc = await asyncio.create_subprocess_exec(\n         str(driver_executable),\n         stdin=asyncio.subprocess.PIPE,\n         stdout=asyncio.subprocess.PIPE,\n-        stderr=sys.stderr,\n+        stderr=_get_stderr_fileno(),\n         limit=32768,\n     )\n     assert proc.stdout\n", "issue": "Stdout/stderr pipe throws stacktrace if stdout/stderr is mocked by Pytest\nI think more an upstream issue (here) instead of for the Pytest plugin.\r\n\r\nStacktrace:\r\n\r\n```\r\npytest project-name/browser_tests --browser chromium --base-url http://localhost:8000/\r\n============================= test session starts ==============================\r\nplatform linux -- Python 3.8.5, pytest-6.0.1, py-1.9.0, pluggy-0.13.1\r\nbaseurl: http://localhost:8000/\r\ndjango: settings: config.settings.test (from option)\r\nUsing --randomly-seed=1\r\nrootdir: /home/runner/work/project-name/project-name, configfile: setup.cfg\r\nplugins: freezegun-0.4.2, base-url-1.4.2, playwright-0.0.5, cov-2.10.0, sugar-0.9.4, django-3.9.0, randomly-3.4.1, celery-4.4.7, factoryboy-2.0.3, Faker-4.1.1, env-0.6.2\r\ncollected 15 items\r\n\r\nproject-name/browser_tests/test_internal_manager_dashboard.py E [  6%]\r\n\r\n\r\n==================================== ERRORS ====================================\r\n_ ERROR at setup of test123[chromium] _\r\n\r\nlaunch_browser = <function launch_browser.<locals>.launch at 0x7f6bc73de430>\r\n\r\n    @pytest.fixture(scope=\"session\")\r\n    def browser(launch_browser: Callable[[], Browser]) -> Generator[Browser, None, None]:\r\n>       browser = launch_browser()\r\n\r\n/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/site-packages/pytest_playwright/pytest_playwright.py:114: \r\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \r\n/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/site-packages/pytest_playwright/pytest_playwright.py:97: in launch\r\n    pw_context = sync_playwright()\r\n/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/site-packages/playwright/__init__.py:27: in sync_playwright\r\n    return SyncPlaywrightContextManager()\r\n/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/site-packages/playwright/main.py:72: in __init__\r\n    self._connection = run_driver()\r\n/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/site-packages/playwright/main.py:67: in run_driver\r\n    return loop.run_until_complete(run_driver_async())\r\n/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/asyncio/base_events.py:616: in run_until_complete\r\n    return future.result()\r\n/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/site-packages/playwright/main.py:48: in run_driver_async\r\n    proc = await asyncio.create_subprocess_exec(\r\n/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/asyncio/subprocess.py:236: in create_subprocess_exec\r\n    transport, protocol = await loop.subprocess_exec(\r\n/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/asyncio/base_events.py:1630: in subprocess_exec\r\n    transport = await self._make_subprocess_transport(\r\n/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/asyncio/unix_events.py:197: in _make_subprocess_transport\r\n    transp = _UnixSubprocessTransport(self, protocol, args, shell,\r\n/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/asyncio/base_subprocess.py:36: in __init__\r\n    self._start(args=args, shell=shell, stdin=stdin, stdout=stdout,\r\n/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/asyncio/unix_events.py:789: in _start\r\n    self._proc = subprocess.Popen(\r\n/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/subprocess.py:804: in __init__\r\n    errread, errwrite) = self._get_handles(stdin, stdout, stderr)\r\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \r\n\r\nself = <subprocess.Popen object at 0x7f6bc73dfa60>\r\nstdin = <socket.socket [closed] fd=-1, family=AddressFamily.AF_UNIX, type=SocketKind.SOCK_STREAM, proto=0>\r\nstdout = -1, stderr = <_io.TextIOWrapper encoding='UTF-8'>\r\n\r\n    def _get_handles(self, stdin, stdout, stderr):\r\n        \"\"\"Construct and return tuple with IO objects:\r\n        p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite\r\n        \"\"\"\r\n        p2cread, p2cwrite = -1, -1\r\n        c2pread, c2pwrite = -1, -1\r\n        errread, errwrite = -1, -1\r\n    \r\n        if stdin is None:\r\n            pass\r\n        elif stdin == PIPE:\r\n            p2cread, p2cwrite = os.pipe()\r\n        elif stdin == DEVNULL:\r\n            p2cread = self._get_devnull()\r\n        elif isinstance(stdin, int):\r\n            p2cread = stdin\r\n        else:\r\n            # Assuming file-like object\r\n            p2cread = stdin.fileno()\r\n    \r\n        if stdout is None:\r\n            pass\r\n        elif stdout == PIPE:\r\n            c2pread, c2pwrite = os.pipe()\r\n        elif stdout == DEVNULL:\r\n            c2pwrite = self._get_devnull()\r\n        elif isinstance(stdout, int):\r\n            c2pwrite = stdout\r\n        else:\r\n            # Assuming file-like object\r\n            c2pwrite = stdout.fileno()\r\n    \r\n        if stderr is None:\r\n            pass\r\n        elif stderr == PIPE:\r\n            errread, errwrite = os.pipe()\r\n        elif stderr == STDOUT:\r\n            if c2pwrite != -1:\r\n                errwrite = c2pwrite\r\n            else: # child's stdout is not set, use parent's stdout\r\n                errwrite = sys.__stdout__.fileno()\r\n        elif stderr == DEVNULL:\r\n            errwrite = self._get_devnull()\r\n        elif isinstance(stderr, int):\r\n            errwrite = stderr\r\n        else:\r\n            # Assuming file-like object\r\n>           errwrite = stderr.fileno()\r\nE           io.UnsupportedOperation: fileno\r\n\r\n/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/subprocess.py:1504: UnsupportedOperation\r\n---------------------------- Captured stdout setup -----------------------------\r\nkektus <_io.TextIOWrapper encoding='UTF-8'>\r\n=========================== short test summary info ============================\r\nERROR project-name/browser_tests/test123.py::test123[chromium]\r\n!!!!!!!!!!!!!!!!!!!!!!!!!! stopping after 1 failures !!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n=============================== 1 error in 0.67s ===============================\r\nMakefile:23: recipe for target 'browser_test' failed\r\n\r\n```\r\n\r\nUsing the `-s` parameter is a workaround for that. Issue is persistent since https://github.com/microsoft/playwright-python/pull/145.\n", "before_files": [{"content": "# Copyright (c) Microsoft Corporation.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport asyncio\nimport subprocess\nimport sys\nfrom typing import Any\n\nfrom greenlet import greenlet\n\nfrom playwright.async_api import Playwright as AsyncPlaywright\nfrom playwright.connection import Connection\nfrom playwright.helper import Error\nfrom playwright.object_factory import create_remote_object\nfrom playwright.path_utils import get_file_dirname\nfrom playwright.playwright import Playwright\nfrom playwright.sync_api import Playwright as SyncPlaywright\nfrom playwright.sync_base import dispatcher_fiber, set_dispatcher_fiber\n\n\ndef compute_driver_name() -> str:\n    platform = sys.platform\n    if platform == \"darwin\":\n        result = \"driver-macos\"\n    elif platform == \"linux\":\n        result = \"driver-linux\"\n    elif platform == \"win32\":\n        result = \"driver-win.exe\"\n    return result\n\n\nasync def run_driver_async() -> Connection:\n    package_path = get_file_dirname()\n    driver_name = compute_driver_name()\n    driver_executable = package_path / \"drivers\" / driver_name\n\n    proc = await asyncio.create_subprocess_exec(\n        str(driver_executable),\n        stdin=asyncio.subprocess.PIPE,\n        stdout=asyncio.subprocess.PIPE,\n        stderr=sys.stderr,\n        limit=32768,\n    )\n    assert proc.stdout\n    assert proc.stdin\n    connection = Connection(\n        proc.stdout, proc.stdin, create_remote_object, asyncio.get_event_loop()\n    )\n    return connection\n\n\ndef run_driver() -> Connection:\n    loop = asyncio.get_event_loop()\n    if loop.is_running():\n        raise Error(\"Can only run one Playwright at a time.\")\n    return loop.run_until_complete(run_driver_async())\n\n\nclass SyncPlaywrightContextManager:\n    def __init__(self) -> None:\n        self._connection = run_driver()\n        self._playwright: SyncPlaywright\n\n    def __enter__(self) -> SyncPlaywright:\n        g_self = greenlet.getcurrent()\n\n        def callback_wrapper(playwright_impl: Playwright) -> None:\n            self._playwright = SyncPlaywright(playwright_impl)\n            g_self.switch()\n\n        self._connection.call_on_object_with_known_name(\"Playwright\", callback_wrapper)\n        set_dispatcher_fiber(greenlet(lambda: self._connection.run_sync()))\n        dispatcher_fiber().switch()\n        return self._playwright\n\n    def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:\n        self._connection.stop_sync()\n\n\nclass AsyncPlaywrightContextManager:\n    def __init__(self) -> None:\n        self._connection: Connection\n\n    async def __aenter__(self) -> AsyncPlaywright:\n        self._connection = await run_driver_async()\n        self._connection.run_async()\n        return AsyncPlaywright(\n            await self._connection.wait_for_object_with_known_name(\"Playwright\")\n        )\n\n    async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:\n        self._connection.stop_async()\n\n\nif sys.platform == \"win32\":\n    # Use ProactorEventLoop in 3.7, which is default in 3.8\n    loop = asyncio.ProactorEventLoop()\n    asyncio.set_event_loop(loop)\n\n\ndef main() -> None:\n    if \"install\" not in sys.argv:\n        print('Run \"python -m playwright install\" to complete installation')\n        return\n    package_path = get_file_dirname()\n    driver_name = compute_driver_name()\n    driver_executable = package_path / \"drivers\" / driver_name\n    print(\"Installing the browsers...\")\n    subprocess.check_call(f\"{driver_executable} install\", shell=True)\n\n    print(\"Playwright is now ready for use\")\n", "path": "playwright/main.py"}], "after_files": [{"content": "# Copyright (c) Microsoft Corporation.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport asyncio\nimport io\nimport subprocess\nimport sys\nfrom typing import Any\n\nfrom greenlet import greenlet\n\nfrom playwright.async_api import Playwright as AsyncPlaywright\nfrom playwright.connection import Connection\nfrom playwright.helper import Error\nfrom playwright.object_factory import create_remote_object\nfrom playwright.path_utils import get_file_dirname\nfrom playwright.playwright import Playwright\nfrom playwright.sync_api import Playwright as SyncPlaywright\nfrom playwright.sync_base import dispatcher_fiber, set_dispatcher_fiber\n\n\ndef compute_driver_name() -> str:\n    platform = sys.platform\n    if platform == \"darwin\":\n        result = \"driver-macos\"\n    elif platform == \"linux\":\n        result = \"driver-linux\"\n    elif platform == \"win32\":\n        result = \"driver-win.exe\"\n    return result\n\n\nasync def run_driver_async() -> Connection:\n    package_path = get_file_dirname()\n    driver_name = compute_driver_name()\n    driver_executable = package_path / \"drivers\" / driver_name\n\n    # Sourced from: https://github.com/pytest-dev/pytest/blob/49827adcb9256c9c9c06a25729421dcc3c385edc/src/_pytest/faulthandler.py#L73-L80\n    def _get_stderr_fileno() -> int:\n        try:\n            return sys.stderr.fileno()\n        except io.UnsupportedOperation:\n            # pytest-xdist monkeypatches sys.stderr with an object that is not an actual file.\n            # https://docs.python.org/3/library/faulthandler.html#issue-with-file-descriptors\n            # This is potentially dangerous, but the best we can do.\n            return sys.__stderr__.fileno()\n\n    proc = await asyncio.create_subprocess_exec(\n        str(driver_executable),\n        stdin=asyncio.subprocess.PIPE,\n        stdout=asyncio.subprocess.PIPE,\n        stderr=_get_stderr_fileno(),\n        limit=32768,\n    )\n    assert proc.stdout\n    assert proc.stdin\n    connection = Connection(\n        proc.stdout, proc.stdin, create_remote_object, asyncio.get_event_loop()\n    )\n    return connection\n\n\ndef run_driver() -> Connection:\n    loop = asyncio.get_event_loop()\n    if loop.is_running():\n        raise Error(\"Can only run one Playwright at a time.\")\n    return loop.run_until_complete(run_driver_async())\n\n\nclass SyncPlaywrightContextManager:\n    def __init__(self) -> None:\n        self._connection = run_driver()\n        self._playwright: SyncPlaywright\n\n    def __enter__(self) -> SyncPlaywright:\n        g_self = greenlet.getcurrent()\n\n        def callback_wrapper(playwright_impl: Playwright) -> None:\n            self._playwright = SyncPlaywright(playwright_impl)\n            g_self.switch()\n\n        self._connection.call_on_object_with_known_name(\"Playwright\", callback_wrapper)\n        set_dispatcher_fiber(greenlet(lambda: self._connection.run_sync()))\n        dispatcher_fiber().switch()\n        return self._playwright\n\n    def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:\n        self._connection.stop_sync()\n\n\nclass AsyncPlaywrightContextManager:\n    def __init__(self) -> None:\n        self._connection: Connection\n\n    async def __aenter__(self) -> AsyncPlaywright:\n        self._connection = await run_driver_async()\n        self._connection.run_async()\n        return AsyncPlaywright(\n            await self._connection.wait_for_object_with_known_name(\"Playwright\")\n        )\n\n    async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:\n        self._connection.stop_async()\n\n\nif sys.platform == \"win32\":\n    # Use ProactorEventLoop in 3.7, which is default in 3.8\n    loop = asyncio.ProactorEventLoop()\n    asyncio.set_event_loop(loop)\n\n\ndef main() -> None:\n    if \"install\" not in sys.argv:\n        print('Run \"python -m playwright install\" to complete installation')\n        return\n    package_path = get_file_dirname()\n    driver_name = compute_driver_name()\n    driver_executable = package_path / \"drivers\" / driver_name\n    print(\"Installing the browsers...\")\n    subprocess.check_call(f\"{driver_executable} install\", shell=True)\n\n    print(\"Playwright is now ready for use\")\n", "path": "playwright/main.py"}]}