We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
script magics cause terminal spam
since the addition of script magics in cdde5bba8 one gets a _which_ error message outputted to the terminal on each start:
e.g. if no python3 is available:

```
$ ipython
which: no python3 in (/scratch/jtaylor/progs/localinst/lib/ccache:/scratch/jtaylor/progs/localinst/bin:/scratch/jtaylor/progs/Reflex/software/bin:/usr/lib/qt-3.3/bin:/usr/kerberos/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/jtaylor/gasgano/bin:/scisoft/bin:/home/jtaylor/scripts:/scratch/jtaylor/progs/root/bin)
```


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `IPython/utils/_process_posix.py`
Content:
```
1 """Posix-specific implementation of process utilities.
2 
3 This file is only meant to be imported by process.py, not by end-users.
4 """
5 
6 #-----------------------------------------------------------------------------
7 #  Copyright (C) 2010-2011  The IPython Development Team
8 #
9 #  Distributed under the terms of the BSD License.  The full license is in
10 #  the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
12 
13 #-----------------------------------------------------------------------------
14 # Imports
15 #-----------------------------------------------------------------------------
16 from __future__ import print_function
17 
18 # Stdlib
19 import subprocess as sp
20 import sys
21 
22 from IPython.external import pexpect
23 
24 # Our own
25 from .autoattr import auto_attr
26 from ._process_common import getoutput, arg_split
27 from IPython.utils import text
28 from IPython.utils import py3compat
29 from IPython.utils.encoding import DEFAULT_ENCODING
30 
31 #-----------------------------------------------------------------------------
32 # Function definitions
33 #-----------------------------------------------------------------------------
34 
35 def _find_cmd(cmd):
36     """Find the full path to a command using which."""
37 
38     path = sp.Popen(['/usr/bin/env', 'which', cmd],
39                     stdout=sp.PIPE).communicate()[0]
40     return py3compat.bytes_to_str(path)
41 
42 
43 class ProcessHandler(object):
44     """Execute subprocesses under the control of pexpect.
45     """
46     # Timeout in seconds to wait on each reading of the subprocess' output.
47     # This should not be set too low to avoid cpu overusage from our side,
48     # since we read in a loop whose period is controlled by this timeout.
49     read_timeout = 0.05
50 
51     # Timeout to give a process if we receive SIGINT, between sending the
52     # SIGINT to the process and forcefully terminating it.
53     terminate_timeout = 0.2
54 
55     # File object where stdout and stderr of the subprocess will be written
56     logfile = None
57 
58     # Shell to call for subprocesses to execute
59     sh = None
60 
61     @auto_attr
62     def sh(self):
63         sh = pexpect.which('sh')
64         if sh is None:
65             raise OSError('"sh" shell not found')
66         return sh
67 
68     def __init__(self, logfile=None, read_timeout=None, terminate_timeout=None):
69         """Arguments are used for pexpect calls."""
70         self.read_timeout = (ProcessHandler.read_timeout if read_timeout is
71                              None else read_timeout)
72         self.terminate_timeout = (ProcessHandler.terminate_timeout if
73                                   terminate_timeout is None else
74                                   terminate_timeout)
75         self.logfile = sys.stdout if logfile is None else logfile
76 
77     def getoutput(self, cmd):
78         """Run a command and return its stdout/stderr as a string.
79 
80         Parameters
81         ----------
82         cmd : str
83           A command to be executed in the system shell.
84 
85         Returns
86         -------
87         output : str
88           A string containing the combination of stdout and stderr from the
89         subprocess, in whatever order the subprocess originally wrote to its
90         file descriptors (so the order of the information in this string is the
91         correct order as would be seen if running the command in a terminal).
92         """
93         try:
94             return pexpect.run(self.sh, args=['-c', cmd]).replace('\r\n', '\n')
95         except KeyboardInterrupt:
96             print('^C', file=sys.stderr, end='')
97 
98     def getoutput_pexpect(self, cmd):
99         """Run a command and return its stdout/stderr as a string.
100 
101         Parameters
102         ----------
103         cmd : str
104           A command to be executed in the system shell.
105 
106         Returns
107         -------
108         output : str
109           A string containing the combination of stdout and stderr from the
110         subprocess, in whatever order the subprocess originally wrote to its
111         file descriptors (so the order of the information in this string is the
112         correct order as would be seen if running the command in a terminal).
113         """
114         try:
115             return pexpect.run(self.sh, args=['-c', cmd]).replace('\r\n', '\n')
116         except KeyboardInterrupt:
117             print('^C', file=sys.stderr, end='')
118 
119     def system(self, cmd):
120         """Execute a command in a subshell.
121 
122         Parameters
123         ----------
124         cmd : str
125           A command to be executed in the system shell.
126 
127         Returns
128         -------
129         int : child's exitstatus
130         """
131         # Get likely encoding for the output.
132         enc = DEFAULT_ENCODING
133         
134         # Patterns to match on the output, for pexpect.  We read input and
135         # allow either a short timeout or EOF
136         patterns = [pexpect.TIMEOUT, pexpect.EOF]
137         # the index of the EOF pattern in the list.
138         # even though we know it's 1, this call means we don't have to worry if
139         # we change the above list, and forget to change this value:
140         EOF_index = patterns.index(pexpect.EOF)
141         # The size of the output stored so far in the process output buffer.
142         # Since pexpect only appends to this buffer, each time we print we
143         # record how far we've printed, so that next time we only print *new*
144         # content from the buffer.
145         out_size = 0
146         try:
147             # Since we're not really searching the buffer for text patterns, we
148             # can set pexpect's search window to be tiny and it won't matter.
149             # We only search for the 'patterns' timeout or EOF, which aren't in
150             # the text itself.
151             #child = pexpect.spawn(pcmd, searchwindowsize=1)
152             if hasattr(pexpect, 'spawnb'):
153                 child = pexpect.spawnb(self.sh, args=['-c', cmd]) # Pexpect-U
154             else:
155                 child = pexpect.spawn(self.sh, args=['-c', cmd])  # Vanilla Pexpect
156             flush = sys.stdout.flush
157             while True:
158                 # res is the index of the pattern that caused the match, so we
159                 # know whether we've finished (if we matched EOF) or not
160                 res_idx = child.expect_list(patterns, self.read_timeout)
161                 print(child.before[out_size:].decode(enc, 'replace'), end='')
162                 flush()
163                 if res_idx==EOF_index:
164                     break
165                 # Update the pointer to what we've already printed
166                 out_size = len(child.before)
167         except KeyboardInterrupt:
168             # We need to send ^C to the process.  The ascii code for '^C' is 3
169             # (the character is known as ETX for 'End of Text', see
170             # curses.ascii.ETX).
171             child.sendline(chr(3))
172             # Read and print any more output the program might produce on its
173             # way out.
174             try:
175                 out_size = len(child.before)
176                 child.expect_list(patterns, self.terminate_timeout)
177                 print(child.before[out_size:].decode(enc, 'replace'), end='')
178                 sys.stdout.flush()
179             except KeyboardInterrupt:
180                 # Impatient users tend to type it multiple times
181                 pass
182             finally:
183                 # Ensure the subprocess really is terminated
184                 child.terminate(force=True)
185         # add isalive check, to ensure exitstatus is set:
186         child.isalive()
187         return child.exitstatus
188 
189 
190 # Make system() with a functional interface for outside use.  Note that we use
191 # getoutput() from the _common utils, which is built on top of popen(). Using
192 # pexpect to get subprocess output produces difficult to parse output, since
193 # programs think they are talking to a tty and produce highly formatted output
194 # (ls is a good example) that makes them hard.
195 system = ProcessHandler().system
196 
197 
198 
199
```
--- 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/IPython/utils/_process_posix.py b/IPython/utils/_process_posix.py
--- a/IPython/utils/_process_posix.py
+++ b/IPython/utils/_process_posix.py
@@ -36,7 +36,7 @@
     """Find the full path to a command using which."""
 
     path = sp.Popen(['/usr/bin/env', 'which', cmd],
-                    stdout=sp.PIPE).communicate()[0]
+                    stdout=sp.PIPE, stderr=sp.PIPE).communicate()[0]
     return py3compat.bytes_to_str(path)

{"golden_diff": "diff --git a/IPython/utils/_process_posix.py b/IPython/utils/_process_posix.py\n--- a/IPython/utils/_process_posix.py\n+++ b/IPython/utils/_process_posix.py\n@@ -36,7 +36,7 @@\n     \"\"\"Find the full path to a command using which.\"\"\"\n \n     path = sp.Popen(['/usr/bin/env', 'which', cmd],\n-                    stdout=sp.PIPE).communicate()[0]\n+                    stdout=sp.PIPE, stderr=sp.PIPE).communicate()[0]\n     return py3compat.bytes_to_str(path)\n", "issue": "script magics cause terminal spam\nsince the addition of script magics in cdde5bba8 one gets a _which_ error message outputted to the terminal on each start:\ne.g. if no python3 is available:\n\n```\n$ ipython\nwhich: no python3 in (/scratch/jtaylor/progs/localinst/lib/ccache:/scratch/jtaylor/progs/localinst/bin:/scratch/jtaylor/progs/Reflex/software/bin:/usr/lib/qt-3.3/bin:/usr/kerberos/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/jtaylor/gasgano/bin:/scisoft/bin:/home/jtaylor/scripts:/scratch/jtaylor/progs/root/bin)\n```\n\n", "before_files": [{"content": "\"\"\"Posix-specific implementation of process utilities.\n\nThis file is only meant to be imported by process.py, not by end-users.\n\"\"\"\n\n#-----------------------------------------------------------------------------\n#  Copyright (C) 2010-2011  The IPython Development Team\n#\n#  Distributed under the terms of the BSD License.  The full license is in\n#  the file COPYING, distributed as part of this software.\n#-----------------------------------------------------------------------------\n\n#-----------------------------------------------------------------------------\n# Imports\n#-----------------------------------------------------------------------------\nfrom __future__ import print_function\n\n# Stdlib\nimport subprocess as sp\nimport sys\n\nfrom IPython.external import pexpect\n\n# Our own\nfrom .autoattr import auto_attr\nfrom ._process_common import getoutput, arg_split\nfrom IPython.utils import text\nfrom IPython.utils import py3compat\nfrom IPython.utils.encoding import DEFAULT_ENCODING\n\n#-----------------------------------------------------------------------------\n# Function definitions\n#-----------------------------------------------------------------------------\n\ndef _find_cmd(cmd):\n    \"\"\"Find the full path to a command using which.\"\"\"\n\n    path = sp.Popen(['/usr/bin/env', 'which', cmd],\n                    stdout=sp.PIPE).communicate()[0]\n    return py3compat.bytes_to_str(path)\n\n\nclass ProcessHandler(object):\n    \"\"\"Execute subprocesses under the control of pexpect.\n    \"\"\"\n    # Timeout in seconds to wait on each reading of the subprocess' output.\n    # This should not be set too low to avoid cpu overusage from our side,\n    # since we read in a loop whose period is controlled by this timeout.\n    read_timeout = 0.05\n\n    # Timeout to give a process if we receive SIGINT, between sending the\n    # SIGINT to the process and forcefully terminating it.\n    terminate_timeout = 0.2\n\n    # File object where stdout and stderr of the subprocess will be written\n    logfile = None\n\n    # Shell to call for subprocesses to execute\n    sh = None\n\n    @auto_attr\n    def sh(self):\n        sh = pexpect.which('sh')\n        if sh is None:\n            raise OSError('\"sh\" shell not found')\n        return sh\n\n    def __init__(self, logfile=None, read_timeout=None, terminate_timeout=None):\n        \"\"\"Arguments are used for pexpect calls.\"\"\"\n        self.read_timeout = (ProcessHandler.read_timeout if read_timeout is\n                             None else read_timeout)\n        self.terminate_timeout = (ProcessHandler.terminate_timeout if\n                                  terminate_timeout is None else\n                                  terminate_timeout)\n        self.logfile = sys.stdout if logfile is None else logfile\n\n    def getoutput(self, cmd):\n        \"\"\"Run a command and return its stdout/stderr as a string.\n\n        Parameters\n        ----------\n        cmd : str\n          A command to be executed in the system shell.\n\n        Returns\n        -------\n        output : str\n          A string containing the combination of stdout and stderr from the\n        subprocess, in whatever order the subprocess originally wrote to its\n        file descriptors (so the order of the information in this string is the\n        correct order as would be seen if running the command in a terminal).\n        \"\"\"\n        try:\n            return pexpect.run(self.sh, args=['-c', cmd]).replace('\\r\\n', '\\n')\n        except KeyboardInterrupt:\n            print('^C', file=sys.stderr, end='')\n\n    def getoutput_pexpect(self, cmd):\n        \"\"\"Run a command and return its stdout/stderr as a string.\n\n        Parameters\n        ----------\n        cmd : str\n          A command to be executed in the system shell.\n\n        Returns\n        -------\n        output : str\n          A string containing the combination of stdout and stderr from the\n        subprocess, in whatever order the subprocess originally wrote to its\n        file descriptors (so the order of the information in this string is the\n        correct order as would be seen if running the command in a terminal).\n        \"\"\"\n        try:\n            return pexpect.run(self.sh, args=['-c', cmd]).replace('\\r\\n', '\\n')\n        except KeyboardInterrupt:\n            print('^C', file=sys.stderr, end='')\n\n    def system(self, cmd):\n        \"\"\"Execute a command in a subshell.\n\n        Parameters\n        ----------\n        cmd : str\n          A command to be executed in the system shell.\n\n        Returns\n        -------\n        int : child's exitstatus\n        \"\"\"\n        # Get likely encoding for the output.\n        enc = DEFAULT_ENCODING\n        \n        # Patterns to match on the output, for pexpect.  We read input and\n        # allow either a short timeout or EOF\n        patterns = [pexpect.TIMEOUT, pexpect.EOF]\n        # the index of the EOF pattern in the list.\n        # even though we know it's 1, this call means we don't have to worry if\n        # we change the above list, and forget to change this value:\n        EOF_index = patterns.index(pexpect.EOF)\n        # The size of the output stored so far in the process output buffer.\n        # Since pexpect only appends to this buffer, each time we print we\n        # record how far we've printed, so that next time we only print *new*\n        # content from the buffer.\n        out_size = 0\n        try:\n            # Since we're not really searching the buffer for text patterns, we\n            # can set pexpect's search window to be tiny and it won't matter.\n            # We only search for the 'patterns' timeout or EOF, which aren't in\n            # the text itself.\n            #child = pexpect.spawn(pcmd, searchwindowsize=1)\n            if hasattr(pexpect, 'spawnb'):\n                child = pexpect.spawnb(self.sh, args=['-c', cmd]) # Pexpect-U\n            else:\n                child = pexpect.spawn(self.sh, args=['-c', cmd])  # Vanilla Pexpect\n            flush = sys.stdout.flush\n            while True:\n                # res is the index of the pattern that caused the match, so we\n                # know whether we've finished (if we matched EOF) or not\n                res_idx = child.expect_list(patterns, self.read_timeout)\n                print(child.before[out_size:].decode(enc, 'replace'), end='')\n                flush()\n                if res_idx==EOF_index:\n                    break\n                # Update the pointer to what we've already printed\n                out_size = len(child.before)\n        except KeyboardInterrupt:\n            # We need to send ^C to the process.  The ascii code for '^C' is 3\n            # (the character is known as ETX for 'End of Text', see\n            # curses.ascii.ETX).\n            child.sendline(chr(3))\n            # Read and print any more output the program might produce on its\n            # way out.\n            try:\n                out_size = len(child.before)\n                child.expect_list(patterns, self.terminate_timeout)\n                print(child.before[out_size:].decode(enc, 'replace'), end='')\n                sys.stdout.flush()\n            except KeyboardInterrupt:\n                # Impatient users tend to type it multiple times\n                pass\n            finally:\n                # Ensure the subprocess really is terminated\n                child.terminate(force=True)\n        # add isalive check, to ensure exitstatus is set:\n        child.isalive()\n        return child.exitstatus\n\n\n# Make system() with a functional interface for outside use.  Note that we use\n# getoutput() from the _common utils, which is built on top of popen(). Using\n# pexpect to get subprocess output produces difficult to parse output, since\n# programs think they are talking to a tty and produce highly formatted output\n# (ls is a good example) that makes them hard.\nsystem = ProcessHandler().system\n\n\n\n", "path": "IPython/utils/_process_posix.py"}], "after_files": [{"content": "\"\"\"Posix-specific implementation of process utilities.\n\nThis file is only meant to be imported by process.py, not by end-users.\n\"\"\"\n\n#-----------------------------------------------------------------------------\n#  Copyright (C) 2010-2011  The IPython Development Team\n#\n#  Distributed under the terms of the BSD License.  The full license is in\n#  the file COPYING, distributed as part of this software.\n#-----------------------------------------------------------------------------\n\n#-----------------------------------------------------------------------------\n# Imports\n#-----------------------------------------------------------------------------\nfrom __future__ import print_function\n\n# Stdlib\nimport subprocess as sp\nimport sys\n\nfrom IPython.external import pexpect\n\n# Our own\nfrom .autoattr import auto_attr\nfrom ._process_common import getoutput, arg_split\nfrom IPython.utils import text\nfrom IPython.utils import py3compat\nfrom IPython.utils.encoding import DEFAULT_ENCODING\n\n#-----------------------------------------------------------------------------\n# Function definitions\n#-----------------------------------------------------------------------------\n\ndef _find_cmd(cmd):\n    \"\"\"Find the full path to a command using which.\"\"\"\n\n    path = sp.Popen(['/usr/bin/env', 'which', cmd],\n                    stdout=sp.PIPE, stderr=sp.PIPE).communicate()[0]\n    return py3compat.bytes_to_str(path)\n\n\nclass ProcessHandler(object):\n    \"\"\"Execute subprocesses under the control of pexpect.\n    \"\"\"\n    # Timeout in seconds to wait on each reading of the subprocess' output.\n    # This should not be set too low to avoid cpu overusage from our side,\n    # since we read in a loop whose period is controlled by this timeout.\n    read_timeout = 0.05\n\n    # Timeout to give a process if we receive SIGINT, between sending the\n    # SIGINT to the process and forcefully terminating it.\n    terminate_timeout = 0.2\n\n    # File object where stdout and stderr of the subprocess will be written\n    logfile = None\n\n    # Shell to call for subprocesses to execute\n    sh = None\n\n    @auto_attr\n    def sh(self):\n        sh = pexpect.which('sh')\n        if sh is None:\n            raise OSError('\"sh\" shell not found')\n        return sh\n\n    def __init__(self, logfile=None, read_timeout=None, terminate_timeout=None):\n        \"\"\"Arguments are used for pexpect calls.\"\"\"\n        self.read_timeout = (ProcessHandler.read_timeout if read_timeout is\n                             None else read_timeout)\n        self.terminate_timeout = (ProcessHandler.terminate_timeout if\n                                  terminate_timeout is None else\n                                  terminate_timeout)\n        self.logfile = sys.stdout if logfile is None else logfile\n\n    def getoutput(self, cmd):\n        \"\"\"Run a command and return its stdout/stderr as a string.\n\n        Parameters\n        ----------\n        cmd : str\n          A command to be executed in the system shell.\n\n        Returns\n        -------\n        output : str\n          A string containing the combination of stdout and stderr from the\n        subprocess, in whatever order the subprocess originally wrote to its\n        file descriptors (so the order of the information in this string is the\n        correct order as would be seen if running the command in a terminal).\n        \"\"\"\n        try:\n            return pexpect.run(self.sh, args=['-c', cmd]).replace('\\r\\n', '\\n')\n        except KeyboardInterrupt:\n            print('^C', file=sys.stderr, end='')\n\n    def getoutput_pexpect(self, cmd):\n        \"\"\"Run a command and return its stdout/stderr as a string.\n\n        Parameters\n        ----------\n        cmd : str\n          A command to be executed in the system shell.\n\n        Returns\n        -------\n        output : str\n          A string containing the combination of stdout and stderr from the\n        subprocess, in whatever order the subprocess originally wrote to its\n        file descriptors (so the order of the information in this string is the\n        correct order as would be seen if running the command in a terminal).\n        \"\"\"\n        try:\n            return pexpect.run(self.sh, args=['-c', cmd]).replace('\\r\\n', '\\n')\n        except KeyboardInterrupt:\n            print('^C', file=sys.stderr, end='')\n\n    def system(self, cmd):\n        \"\"\"Execute a command in a subshell.\n\n        Parameters\n        ----------\n        cmd : str\n          A command to be executed in the system shell.\n\n        Returns\n        -------\n        int : child's exitstatus\n        \"\"\"\n        # Get likely encoding for the output.\n        enc = DEFAULT_ENCODING\n        \n        # Patterns to match on the output, for pexpect.  We read input and\n        # allow either a short timeout or EOF\n        patterns = [pexpect.TIMEOUT, pexpect.EOF]\n        # the index of the EOF pattern in the list.\n        # even though we know it's 1, this call means we don't have to worry if\n        # we change the above list, and forget to change this value:\n        EOF_index = patterns.index(pexpect.EOF)\n        # The size of the output stored so far in the process output buffer.\n        # Since pexpect only appends to this buffer, each time we print we\n        # record how far we've printed, so that next time we only print *new*\n        # content from the buffer.\n        out_size = 0\n        try:\n            # Since we're not really searching the buffer for text patterns, we\n            # can set pexpect's search window to be tiny and it won't matter.\n            # We only search for the 'patterns' timeout or EOF, which aren't in\n            # the text itself.\n            #child = pexpect.spawn(pcmd, searchwindowsize=1)\n            if hasattr(pexpect, 'spawnb'):\n                child = pexpect.spawnb(self.sh, args=['-c', cmd]) # Pexpect-U\n            else:\n                child = pexpect.spawn(self.sh, args=['-c', cmd])  # Vanilla Pexpect\n            flush = sys.stdout.flush\n            while True:\n                # res is the index of the pattern that caused the match, so we\n                # know whether we've finished (if we matched EOF) or not\n                res_idx = child.expect_list(patterns, self.read_timeout)\n                print(child.before[out_size:].decode(enc, 'replace'), end='')\n                flush()\n                if res_idx==EOF_index:\n                    break\n                # Update the pointer to what we've already printed\n                out_size = len(child.before)\n        except KeyboardInterrupt:\n            # We need to send ^C to the process.  The ascii code for '^C' is 3\n            # (the character is known as ETX for 'End of Text', see\n            # curses.ascii.ETX).\n            child.sendline(chr(3))\n            # Read and print any more output the program might produce on its\n            # way out.\n            try:\n                out_size = len(child.before)\n                child.expect_list(patterns, self.terminate_timeout)\n                print(child.before[out_size:].decode(enc, 'replace'), end='')\n                sys.stdout.flush()\n            except KeyboardInterrupt:\n                # Impatient users tend to type it multiple times\n                pass\n            finally:\n                # Ensure the subprocess really is terminated\n                child.terminate(force=True)\n        # add isalive check, to ensure exitstatus is set:\n        child.isalive()\n        return child.exitstatus\n\n\n# Make system() with a functional interface for outside use.  Note that we use\n# getoutput() from the _common utils, which is built on top of popen(). Using\n# pexpect to get subprocess output produces difficult to parse output, since\n# programs think they are talking to a tty and produce highly formatted output\n# (ls is a good example) that makes them hard.\nsystem = ProcessHandler().system\n\n\n\n", "path": "IPython/utils/_process_posix.py"}]}