We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
PTK OSError Bad file descriptor
When I run a command like `cat foo.json | py -m json.tool`, xonsh got crash with following errors after the command pipe finish (with output correct). I'm not sure it's a ptk issue or xonsh one. Either way I think we should add some `try-catch` for not crashing the shell at least and for stability.

```
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/xonsh/ptk/shortcuts.py", line 108, in prompt
    document = cli.run(reset_current_buffer=False)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/prompt_toolkit/interface.py", line 394, in run
    self.eventloop.run(self.input, self.create_eventloop_callbacks())
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/prompt_toolkit/eventloop/posix.py", line 93, in run
    self.add_reader(self._schedule_pipe[0], None)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/prompt_toolkit/eventloop/posix.py", line 280, in add_reader
    self.selector.register(fd)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/prompt_toolkit/eventloop/select.py", line 75, in register
    sel.register(fd)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/prompt_toolkit/eventloop/select.py", line 130, in register
    self._sel.register(fd, selectors.EVENT_READ, None)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/selectors.py", line 536, in register
    self._kqueue.control([kev], 0, 0)
OSError: [Errno 9] Bad file descriptor

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.5/bin/xonsh", line 3, in <module>
    main()
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/xonsh/main.py", line 276, in main
    shell.shell.cmdloop()
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/xonsh/ptk/shell.py", line 132, in cmdloop
    line = self.singleline(auto_suggest=auto_suggest)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/xonsh/ptk/shell.py", line 101, in singleline
    line = self.prompter.prompt(**prompt_args)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/xonsh/ptk/shortcuts.py", line 113, in prompt
    eventloop.close()
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/prompt_toolkit/eventloop/posix.py", line 270, in close
    os.close(schedule_pipe[0])
OSError: [Errno 9] Bad file descriptor
```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `xonsh/ptk/shortcuts.py`
Content:
```
1 """A prompt-toolkit inspired shortcut collection."""
2 import builtins
3 import textwrap
4 
5 from prompt_toolkit.interface import CommandLineInterface
6 from prompt_toolkit.enums import EditingMode
7 from prompt_toolkit.utils import DummyContext
8 from prompt_toolkit.shortcuts import (create_prompt_application,
9                                       create_eventloop, create_asyncio_eventloop, create_output)
10 
11 from xonsh.platform import ptk_version_info
12 
13 
14 class Prompter(object):
15 
16     def __init__(self, cli=None, *args, **kwargs):
17         """Implements a prompt that statefully holds a command-line
18         interface.  When used as a context manager, it will return itself
19         on entry and reset itself on exit.
20 
21         Parameters
22         ----------
23         cli : CommandLineInterface or None, optional
24             If this is not a CommandLineInterface object, such an object
25             will be created when the prompt() method is called.
26         """
27         self.cli = cli
28         self.major_minor = ptk_version_info()[:2]
29 
30     def __enter__(self):
31         self.reset()
32         return self
33 
34     def __exit__(self, exc_type, exc_value, traceback):
35         pass
36 
37     def prompt(self, message='', **kwargs):
38         """Get input from the user and return it.
39 
40         This is a wrapper around a lot of prompt_toolkit functionality and
41         can be a replacement for raw_input. (or GNU readline.) If you want
42         to keep your history across several calls, create one
43         `~prompt_toolkit.history.History instance and pass it every
44         time. This function accepts many keyword arguments. Except for the
45         following. they are a proxy to the arguments of
46         create_prompt_application().
47 
48         Parameters
49         ----------
50         patch_stdout : file-like, optional
51             Replace ``sys.stdout`` by a proxy that ensures that print
52             statements from other threads won't destroy the prompt. (They
53             will be printed above the prompt instead.)
54         return_asyncio_coroutine : bool, optional
55             When True, return a asyncio coroutine. (Python >3.3)
56 
57         Notes
58         -----
59         This method was forked from the mainline prompt-toolkit repo.
60         Copyright (c) 2014, Jonathan Slenders, All rights reserved.
61         """
62         patch_stdout = kwargs.pop('patch_stdout', False)
63         return_asyncio_coroutine = kwargs.pop('return_asyncio_coroutine', False)
64         if return_asyncio_coroutine:
65             eventloop = create_asyncio_eventloop()
66         else:
67             eventloop = kwargs.pop('eventloop', None) or create_eventloop()
68 
69         # Create CommandLineInterface.
70         if self.cli is None:
71             if builtins.__xonsh_env__.get('VI_MODE'):
72                 editing_mode = EditingMode.VI
73             else:
74                 editing_mode = EditingMode.EMACS
75             kwargs['editing_mode'] = editing_mode
76             cli = CommandLineInterface(
77                 application=create_prompt_application(message, **kwargs),
78                 eventloop=eventloop,
79                 output=create_output())
80             self.cli = cli
81         else:
82             cli = self.cli
83 
84         # Replace stdout.
85         patch_context = cli.patch_stdout_context() if patch_stdout else DummyContext()
86 
87         # Read input and return it.
88         if return_asyncio_coroutine:
89             # Create an asyncio coroutine and call it.
90             exec_context = {'patch_context': patch_context, 'cli': cli}
91             exec(textwrap.dedent('''
92             import asyncio
93             @asyncio.coroutine
94             def prompt_coro():
95                 with patch_context:
96                     document = yield from cli.run_async(reset_current_buffer=False)
97                     if document:
98                         return document.text
99             '''), exec_context)
100             return exec_context['prompt_coro']()
101         else:
102             # Note: We pass `reset_current_buffer=False`, because that way
103             # it's easy to give DEFAULT_BUFFER a default value, without it
104             # getting erased. We don't have to reset anyway, because this is
105             # the first and only time that this CommandLineInterface will run.
106             try:
107                 with patch_context:
108                     document = cli.run(reset_current_buffer=False)
109 
110                     if document:
111                         return document.text
112             finally:
113                 eventloop.close()
114 
115     def reset(self):
116         """Resets the prompt and cli to a pristine state on this object."""
117         self.cli = None
118
```
--- 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/xonsh/ptk/shortcuts.py b/xonsh/ptk/shortcuts.py
--- a/xonsh/ptk/shortcuts.py
+++ b/xonsh/ptk/shortcuts.py
@@ -9,6 +9,7 @@
                                       create_eventloop, create_asyncio_eventloop, create_output)
 
 from xonsh.platform import ptk_version_info
+import xonsh.tools as xt
 
 
 class Prompter(object):
@@ -106,9 +107,13 @@
             try:
                 with patch_context:
                     document = cli.run(reset_current_buffer=False)
-
                     if document:
                         return document.text
+            except Exception:
+                xt.print_exception()
+                # return something to prevent xonsh crash when any
+                # exceptions raise
+                return ''
             finally:
                 eventloop.close()

{"golden_diff": "diff --git a/xonsh/ptk/shortcuts.py b/xonsh/ptk/shortcuts.py\n--- a/xonsh/ptk/shortcuts.py\n+++ b/xonsh/ptk/shortcuts.py\n@@ -9,6 +9,7 @@\n                                       create_eventloop, create_asyncio_eventloop, create_output)\n \n from xonsh.platform import ptk_version_info\n+import xonsh.tools as xt\n \n \n class Prompter(object):\n@@ -106,9 +107,13 @@\n             try:\n                 with patch_context:\n                     document = cli.run(reset_current_buffer=False)\n-\n                     if document:\n                         return document.text\n+            except Exception:\n+                xt.print_exception()\n+                # return something to prevent xonsh crash when any\n+                # exceptions raise\n+                return ''\n             finally:\n                 eventloop.close()\n", "issue": "PTK OSError Bad file descriptor\nWhen I run a command like `cat foo.json | py -m json.tool`, xonsh got crash with following errors after the command pipe finish (with output correct). I'm not sure it's a ptk issue or xonsh one. Either way I think we should add some `try-catch` for not crashing the shell at least and for stability.\r\n\r\n```\r\nTraceback (most recent call last):\r\n  File \"/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/xonsh/ptk/shortcuts.py\", line 108, in prompt\r\n    document = cli.run(reset_current_buffer=False)\r\n  File \"/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/prompt_toolkit/interface.py\", line 394, in run\r\n    self.eventloop.run(self.input, self.create_eventloop_callbacks())\r\n  File \"/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/prompt_toolkit/eventloop/posix.py\", line 93, in run\r\n    self.add_reader(self._schedule_pipe[0], None)\r\n  File \"/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/prompt_toolkit/eventloop/posix.py\", line 280, in add_reader\r\n    self.selector.register(fd)\r\n  File \"/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/prompt_toolkit/eventloop/select.py\", line 75, in register\r\n    sel.register(fd)\r\n  File \"/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/prompt_toolkit/eventloop/select.py\", line 130, in register\r\n    self._sel.register(fd, selectors.EVENT_READ, None)\r\n  File \"/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/selectors.py\", line 536, in register\r\n    self._kqueue.control([kev], 0, 0)\r\nOSError: [Errno 9] Bad file descriptor\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n  File \"/Library/Frameworks/Python.framework/Versions/3.5/bin/xonsh\", line 3, in <module>\r\n    main()\r\n  File \"/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/xonsh/main.py\", line 276, in main\r\n    shell.shell.cmdloop()\r\n  File \"/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/xonsh/ptk/shell.py\", line 132, in cmdloop\r\n    line = self.singleline(auto_suggest=auto_suggest)\r\n  File \"/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/xonsh/ptk/shell.py\", line 101, in singleline\r\n    line = self.prompter.prompt(**prompt_args)\r\n  File \"/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/xonsh/ptk/shortcuts.py\", line 113, in prompt\r\n    eventloop.close()\r\n  File \"/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/prompt_toolkit/eventloop/posix.py\", line 270, in close\r\n    os.close(schedule_pipe[0])\r\nOSError: [Errno 9] Bad file descriptor\r\n```\n", "before_files": [{"content": "\"\"\"A prompt-toolkit inspired shortcut collection.\"\"\"\nimport builtins\nimport textwrap\n\nfrom prompt_toolkit.interface import CommandLineInterface\nfrom prompt_toolkit.enums import EditingMode\nfrom prompt_toolkit.utils import DummyContext\nfrom prompt_toolkit.shortcuts import (create_prompt_application,\n                                      create_eventloop, create_asyncio_eventloop, create_output)\n\nfrom xonsh.platform import ptk_version_info\n\n\nclass Prompter(object):\n\n    def __init__(self, cli=None, *args, **kwargs):\n        \"\"\"Implements a prompt that statefully holds a command-line\n        interface.  When used as a context manager, it will return itself\n        on entry and reset itself on exit.\n\n        Parameters\n        ----------\n        cli : CommandLineInterface or None, optional\n            If this is not a CommandLineInterface object, such an object\n            will be created when the prompt() method is called.\n        \"\"\"\n        self.cli = cli\n        self.major_minor = ptk_version_info()[:2]\n\n    def __enter__(self):\n        self.reset()\n        return self\n\n    def __exit__(self, exc_type, exc_value, traceback):\n        pass\n\n    def prompt(self, message='', **kwargs):\n        \"\"\"Get input from the user and return it.\n\n        This is a wrapper around a lot of prompt_toolkit functionality and\n        can be a replacement for raw_input. (or GNU readline.) If you want\n        to keep your history across several calls, create one\n        `~prompt_toolkit.history.History instance and pass it every\n        time. This function accepts many keyword arguments. Except for the\n        following. they are a proxy to the arguments of\n        create_prompt_application().\n\n        Parameters\n        ----------\n        patch_stdout : file-like, optional\n            Replace ``sys.stdout`` by a proxy that ensures that print\n            statements from other threads won't destroy the prompt. (They\n            will be printed above the prompt instead.)\n        return_asyncio_coroutine : bool, optional\n            When True, return a asyncio coroutine. (Python >3.3)\n\n        Notes\n        -----\n        This method was forked from the mainline prompt-toolkit repo.\n        Copyright (c) 2014, Jonathan Slenders, All rights reserved.\n        \"\"\"\n        patch_stdout = kwargs.pop('patch_stdout', False)\n        return_asyncio_coroutine = kwargs.pop('return_asyncio_coroutine', False)\n        if return_asyncio_coroutine:\n            eventloop = create_asyncio_eventloop()\n        else:\n            eventloop = kwargs.pop('eventloop', None) or create_eventloop()\n\n        # Create CommandLineInterface.\n        if self.cli is None:\n            if builtins.__xonsh_env__.get('VI_MODE'):\n                editing_mode = EditingMode.VI\n            else:\n                editing_mode = EditingMode.EMACS\n            kwargs['editing_mode'] = editing_mode\n            cli = CommandLineInterface(\n                application=create_prompt_application(message, **kwargs),\n                eventloop=eventloop,\n                output=create_output())\n            self.cli = cli\n        else:\n            cli = self.cli\n\n        # Replace stdout.\n        patch_context = cli.patch_stdout_context() if patch_stdout else DummyContext()\n\n        # Read input and return it.\n        if return_asyncio_coroutine:\n            # Create an asyncio coroutine and call it.\n            exec_context = {'patch_context': patch_context, 'cli': cli}\n            exec(textwrap.dedent('''\n            import asyncio\n            @asyncio.coroutine\n            def prompt_coro():\n                with patch_context:\n                    document = yield from cli.run_async(reset_current_buffer=False)\n                    if document:\n                        return document.text\n            '''), exec_context)\n            return exec_context['prompt_coro']()\n        else:\n            # Note: We pass `reset_current_buffer=False`, because that way\n            # it's easy to give DEFAULT_BUFFER a default value, without it\n            # getting erased. We don't have to reset anyway, because this is\n            # the first and only time that this CommandLineInterface will run.\n            try:\n                with patch_context:\n                    document = cli.run(reset_current_buffer=False)\n\n                    if document:\n                        return document.text\n            finally:\n                eventloop.close()\n\n    def reset(self):\n        \"\"\"Resets the prompt and cli to a pristine state on this object.\"\"\"\n        self.cli = None\n", "path": "xonsh/ptk/shortcuts.py"}], "after_files": [{"content": "\"\"\"A prompt-toolkit inspired shortcut collection.\"\"\"\nimport builtins\nimport textwrap\n\nfrom prompt_toolkit.interface import CommandLineInterface\nfrom prompt_toolkit.enums import EditingMode\nfrom prompt_toolkit.utils import DummyContext\nfrom prompt_toolkit.shortcuts import (create_prompt_application,\n                                      create_eventloop, create_asyncio_eventloop, create_output)\n\nfrom xonsh.platform import ptk_version_info\nimport xonsh.tools as xt\n\n\nclass Prompter(object):\n\n    def __init__(self, cli=None, *args, **kwargs):\n        \"\"\"Implements a prompt that statefully holds a command-line\n        interface.  When used as a context manager, it will return itself\n        on entry and reset itself on exit.\n\n        Parameters\n        ----------\n        cli : CommandLineInterface or None, optional\n            If this is not a CommandLineInterface object, such an object\n            will be created when the prompt() method is called.\n        \"\"\"\n        self.cli = cli\n        self.major_minor = ptk_version_info()[:2]\n\n    def __enter__(self):\n        self.reset()\n        return self\n\n    def __exit__(self, exc_type, exc_value, traceback):\n        pass\n\n    def prompt(self, message='', **kwargs):\n        \"\"\"Get input from the user and return it.\n\n        This is a wrapper around a lot of prompt_toolkit functionality and\n        can be a replacement for raw_input. (or GNU readline.) If you want\n        to keep your history across several calls, create one\n        `~prompt_toolkit.history.History instance and pass it every\n        time. This function accepts many keyword arguments. Except for the\n        following. they are a proxy to the arguments of\n        create_prompt_application().\n\n        Parameters\n        ----------\n        patch_stdout : file-like, optional\n            Replace ``sys.stdout`` by a proxy that ensures that print\n            statements from other threads won't destroy the prompt. (They\n            will be printed above the prompt instead.)\n        return_asyncio_coroutine : bool, optional\n            When True, return a asyncio coroutine. (Python >3.3)\n\n        Notes\n        -----\n        This method was forked from the mainline prompt-toolkit repo.\n        Copyright (c) 2014, Jonathan Slenders, All rights reserved.\n        \"\"\"\n        patch_stdout = kwargs.pop('patch_stdout', False)\n        return_asyncio_coroutine = kwargs.pop('return_asyncio_coroutine', False)\n        if return_asyncio_coroutine:\n            eventloop = create_asyncio_eventloop()\n        else:\n            eventloop = kwargs.pop('eventloop', None) or create_eventloop()\n\n        # Create CommandLineInterface.\n        if self.cli is None:\n            if builtins.__xonsh_env__.get('VI_MODE'):\n                editing_mode = EditingMode.VI\n            else:\n                editing_mode = EditingMode.EMACS\n            kwargs['editing_mode'] = editing_mode\n            cli = CommandLineInterface(\n                application=create_prompt_application(message, **kwargs),\n                eventloop=eventloop,\n                output=create_output())\n            self.cli = cli\n        else:\n            cli = self.cli\n\n        # Replace stdout.\n        patch_context = cli.patch_stdout_context() if patch_stdout else DummyContext()\n\n        # Read input and return it.\n        if return_asyncio_coroutine:\n            # Create an asyncio coroutine and call it.\n            exec_context = {'patch_context': patch_context, 'cli': cli}\n            exec(textwrap.dedent('''\n            import asyncio\n            @asyncio.coroutine\n            def prompt_coro():\n                with patch_context:\n                    document = yield from cli.run_async(reset_current_buffer=False)\n                    if document:\n                        return document.text\n            '''), exec_context)\n            return exec_context['prompt_coro']()\n        else:\n            # Note: We pass `reset_current_buffer=False`, because that way\n            # it's easy to give DEFAULT_BUFFER a default value, without it\n            # getting erased. We don't have to reset anyway, because this is\n            # the first and only time that this CommandLineInterface will run.\n            try:\n                with patch_context:\n                    document = cli.run(reset_current_buffer=False)\n                    if document:\n                        return document.text\n            except Exception:\n                xt.print_exception()\n                # return something to prevent xonsh crash when any\n                # exceptions raise\n                return ''\n            finally:\n                eventloop.close()\n\n    def reset(self):\n        \"\"\"Resets the prompt and cli to a pristine state on this object.\"\"\"\n        self.cli = None\n", "path": "xonsh/ptk/shortcuts.py"}]}