We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
exec_create not work with detach=True
Ubuntu 14.04, Python 2.7.12

docker-py 1.5.0 - Ok

```
In [28]: import docker

In [29]: docker.version
Out[29]: '1.5.0'

In [30]: cli = docker.Client()

In [31]: container = cli.create_container('python:2.7.11', command='sleep 1h')

In [32]: cli.start(container['Id'])

In [33]: e = cli.exec_create(container['Id'], 'echo "123"')

In [34]: cli.exec_start(e['Id'], detach=True)
Out[34]: ''
```

docker 1.10.4 - Not working

```
In [9]: import docker

In [10]: docker.version
Out[10]: '1.10.4'

In [11]: cli = docker.Client()

In [12]: container = cli.create_container('python:2.7.11', command='sleep 1h')

In [13]: cli.start(container['Id'])

In [14]: e = cli.exec_create(container['Id'], 'echo "123"')

In [15]: cli.exec_start(e['Id'], detach=True)
^C---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-15-d3ef5f6326d6> in <module>()
----> 1 cli.exec_start(e['Id'], detach=True)

/usr/local/pyenv/versions/2.7.12/lib/python2.7/site-packages/docker/utils/decorators.pyc in wrapper(self, *args, **kwargs)
     33                     )
     34                 )
---> 35             return f(self, *args, **kwargs)
     36         return wrapper
     37     return decorator

/usr/local/pyenv/versions/2.7.12/lib/python2.7/site-packages/docker/api/exec_api.pyc in exec_start(self, exec_id, detach, tty, stream, socket)
     79         if socket:
     80             return self._get_raw_response_socket(res)
---> 81         return self._read_from_socket(res, stream)

/usr/local/pyenv/versions/2.7.12/lib/python2.7/site-packages/docker/client.pyc in _read_from_socket(self, response, stream)
    324             return frames_iter(socket)
    325         else:
--> 326             return six.binary_type().join(frames_iter(socket))
    327 
    328     def _disable_socket_timeout(self, socket):

/usr/local/pyenv/versions/2.7.12/lib/python2.7/site-packages/docker/utils/socket.pyc in frames_iter(socket)
     70     Returns a generator of frames read from socket
     71     """
---> 72     n = next_frame_size(socket)
     73     while n > 0:
     74         yield read(socket, n)

/usr/local/pyenv/versions/2.7.12/lib/python2.7/site-packages/docker/utils/socket.pyc in next_frame_size(socket)
     58     """
     59     try:
---> 60         data = read_exactly(socket, 8)
     61     except SocketError:
     62         return 0

/usr/local/pyenv/versions/2.7.12/lib/python2.7/site-packages/docker/utils/socket.pyc in read_exactly(socket, n)
     43     data = six.binary_type()
     44     while len(data) < n:
---> 45         next_data = read(socket, n - len(data))
     46         if not next_data:
     47             raise SocketError("Unexpected EOF")

/usr/local/pyenv/versions/2.7.12/lib/python2.7/site-packages/docker/utils/socket.pyc in read(socket, n)
     25     # wait for data to become available
     26     if not isinstance(socket, NpipeSocket):
---> 27         select.select([socket], [], [])
     28 
     29     try:

KeyboardInterrupt: 

```


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `docker/api/exec_api.py`
Content:
```
1 import six
2 
3 from .. import errors
4 from .. import utils
5 
6 
7 class ExecApiMixin(object):
8     @utils.minimum_version('1.15')
9     @utils.check_resource
10     def exec_create(self, container, cmd, stdout=True, stderr=True,
11                     stdin=False, tty=False, privileged=False, user=''):
12         """
13         Sets up an exec instance in a running container.
14 
15         Args:
16             container (str): Target container where exec instance will be
17                 created
18             cmd (str or list): Command to be executed
19             stdout (bool): Attach to stdout. Default: ``True``
20             stderr (bool): Attach to stderr. Default: ``True``
21             stdin (bool): Attach to stdin. Default: ``False``
22             tty (bool): Allocate a pseudo-TTY. Default: False
23             privileged (bool): Run as privileged.
24             user (str): User to execute command as. Default: root
25 
26         Returns:
27             (dict): A dictionary with an exec ``Id`` key.
28 
29         Raises:
30             :py:class:`docker.errors.APIError`
31                 If the server returns an error.
32         """
33 
34         if privileged and utils.compare_version('1.19', self._version) < 0:
35             raise errors.InvalidVersion(
36                 'Privileged exec is not supported in API < 1.19'
37             )
38         if user and utils.compare_version('1.19', self._version) < 0:
39             raise errors.InvalidVersion(
40                 'User-specific exec is not supported in API < 1.19'
41             )
42         if isinstance(cmd, six.string_types):
43             cmd = utils.split_command(cmd)
44 
45         data = {
46             'Container': container,
47             'User': user,
48             'Privileged': privileged,
49             'Tty': tty,
50             'AttachStdin': stdin,
51             'AttachStdout': stdout,
52             'AttachStderr': stderr,
53             'Cmd': cmd
54         }
55 
56         url = self._url('/containers/{0}/exec', container)
57         res = self._post_json(url, data=data)
58         return self._result(res, True)
59 
60     @utils.minimum_version('1.16')
61     def exec_inspect(self, exec_id):
62         """
63         Return low-level information about an exec command.
64 
65         Args:
66             exec_id (str): ID of the exec instance
67 
68         Returns:
69             (dict): Dictionary of values returned by the endpoint.
70 
71         Raises:
72             :py:class:`docker.errors.APIError`
73                 If the server returns an error.
74         """
75         if isinstance(exec_id, dict):
76             exec_id = exec_id.get('Id')
77         res = self._get(self._url("/exec/{0}/json", exec_id))
78         return self._result(res, True)
79 
80     @utils.minimum_version('1.15')
81     def exec_resize(self, exec_id, height=None, width=None):
82         """
83         Resize the tty session used by the specified exec command.
84 
85         Args:
86             exec_id (str): ID of the exec instance
87             height (int): Height of tty session
88             width (int): Width of tty session
89         """
90 
91         if isinstance(exec_id, dict):
92             exec_id = exec_id.get('Id')
93 
94         params = {'h': height, 'w': width}
95         url = self._url("/exec/{0}/resize", exec_id)
96         res = self._post(url, params=params)
97         self._raise_for_status(res)
98 
99     @utils.minimum_version('1.15')
100     def exec_start(self, exec_id, detach=False, tty=False, stream=False,
101                    socket=False):
102         """
103         Start a previously set up exec instance.
104 
105         Args:
106             exec_id (str): ID of the exec instance
107             detach (bool): If true, detach from the exec command.
108                 Default: False
109             tty (bool): Allocate a pseudo-TTY. Default: False
110             stream (bool): Stream response data. Default: False
111 
112         Returns:
113             (generator or str): If ``stream=True``, a generator yielding
114             response chunks. A string containing response data otherwise.
115 
116         Raises:
117             :py:class:`docker.errors.APIError`
118                 If the server returns an error.
119         """
120         # we want opened socket if socket == True
121         if isinstance(exec_id, dict):
122             exec_id = exec_id.get('Id')
123 
124         data = {
125             'Tty': tty,
126             'Detach': detach
127         }
128 
129         headers = {} if detach else {
130             'Connection': 'Upgrade',
131             'Upgrade': 'tcp'
132         }
133 
134         res = self._post_json(
135             self._url('/exec/{0}/start', exec_id),
136             headers=headers,
137             data=data,
138             stream=True
139         )
140 
141         if socket:
142             return self._get_raw_response_socket(res)
143         return self._read_from_socket(res, stream)
144
```
--- 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/docker/api/exec_api.py b/docker/api/exec_api.py
--- a/docker/api/exec_api.py
+++ b/docker/api/exec_api.py
@@ -137,7 +137,8 @@
             data=data,
             stream=True
         )
-
+        if detach:
+            return self._result(res)
         if socket:
             return self._get_raw_response_socket(res)
         return self._read_from_socket(res, stream)

{"golden_diff": "diff --git a/docker/api/exec_api.py b/docker/api/exec_api.py\n--- a/docker/api/exec_api.py\n+++ b/docker/api/exec_api.py\n@@ -137,7 +137,8 @@\n             data=data,\n             stream=True\n         )\n-\n+        if detach:\n+            return self._result(res)\n         if socket:\n             return self._get_raw_response_socket(res)\n         return self._read_from_socket(res, stream)\n", "issue": "exec_create not work with detach=True\nUbuntu 14.04, Python 2.7.12\n\ndocker-py 1.5.0 - Ok\n\n```\nIn [28]: import docker\n\nIn [29]: docker.version\nOut[29]: '1.5.0'\n\nIn [30]: cli = docker.Client()\n\nIn [31]: container = cli.create_container('python:2.7.11', command='sleep 1h')\n\nIn [32]: cli.start(container['Id'])\n\nIn [33]: e = cli.exec_create(container['Id'], 'echo \"123\"')\n\nIn [34]: cli.exec_start(e['Id'], detach=True)\nOut[34]: ''\n```\n\ndocker 1.10.4 - Not working\n\n```\nIn [9]: import docker\n\nIn [10]: docker.version\nOut[10]: '1.10.4'\n\nIn [11]: cli = docker.Client()\n\nIn [12]: container = cli.create_container('python:2.7.11', command='sleep 1h')\n\nIn [13]: cli.start(container['Id'])\n\nIn [14]: e = cli.exec_create(container['Id'], 'echo \"123\"')\n\nIn [15]: cli.exec_start(e['Id'], detach=True)\n^C---------------------------------------------------------------------------\nKeyboardInterrupt                         Traceback (most recent call last)\n<ipython-input-15-d3ef5f6326d6> in <module>()\n----> 1 cli.exec_start(e['Id'], detach=True)\n\n/usr/local/pyenv/versions/2.7.12/lib/python2.7/site-packages/docker/utils/decorators.pyc in wrapper(self, *args, **kwargs)\n     33                     )\n     34                 )\n---> 35             return f(self, *args, **kwargs)\n     36         return wrapper\n     37     return decorator\n\n/usr/local/pyenv/versions/2.7.12/lib/python2.7/site-packages/docker/api/exec_api.pyc in exec_start(self, exec_id, detach, tty, stream, socket)\n     79         if socket:\n     80             return self._get_raw_response_socket(res)\n---> 81         return self._read_from_socket(res, stream)\n\n/usr/local/pyenv/versions/2.7.12/lib/python2.7/site-packages/docker/client.pyc in _read_from_socket(self, response, stream)\n    324             return frames_iter(socket)\n    325         else:\n--> 326             return six.binary_type().join(frames_iter(socket))\n    327 \n    328     def _disable_socket_timeout(self, socket):\n\n/usr/local/pyenv/versions/2.7.12/lib/python2.7/site-packages/docker/utils/socket.pyc in frames_iter(socket)\n     70     Returns a generator of frames read from socket\n     71     \"\"\"\n---> 72     n = next_frame_size(socket)\n     73     while n > 0:\n     74         yield read(socket, n)\n\n/usr/local/pyenv/versions/2.7.12/lib/python2.7/site-packages/docker/utils/socket.pyc in next_frame_size(socket)\n     58     \"\"\"\n     59     try:\n---> 60         data = read_exactly(socket, 8)\n     61     except SocketError:\n     62         return 0\n\n/usr/local/pyenv/versions/2.7.12/lib/python2.7/site-packages/docker/utils/socket.pyc in read_exactly(socket, n)\n     43     data = six.binary_type()\n     44     while len(data) < n:\n---> 45         next_data = read(socket, n - len(data))\n     46         if not next_data:\n     47             raise SocketError(\"Unexpected EOF\")\n\n/usr/local/pyenv/versions/2.7.12/lib/python2.7/site-packages/docker/utils/socket.pyc in read(socket, n)\n     25     # wait for data to become available\n     26     if not isinstance(socket, NpipeSocket):\n---> 27         select.select([socket], [], [])\n     28 \n     29     try:\n\nKeyboardInterrupt: \n\n```\n\n", "before_files": [{"content": "import six\n\nfrom .. import errors\nfrom .. import utils\n\n\nclass ExecApiMixin(object):\n    @utils.minimum_version('1.15')\n    @utils.check_resource\n    def exec_create(self, container, cmd, stdout=True, stderr=True,\n                    stdin=False, tty=False, privileged=False, user=''):\n        \"\"\"\n        Sets up an exec instance in a running container.\n\n        Args:\n            container (str): Target container where exec instance will be\n                created\n            cmd (str or list): Command to be executed\n            stdout (bool): Attach to stdout. Default: ``True``\n            stderr (bool): Attach to stderr. Default: ``True``\n            stdin (bool): Attach to stdin. Default: ``False``\n            tty (bool): Allocate a pseudo-TTY. Default: False\n            privileged (bool): Run as privileged.\n            user (str): User to execute command as. Default: root\n\n        Returns:\n            (dict): A dictionary with an exec ``Id`` key.\n\n        Raises:\n            :py:class:`docker.errors.APIError`\n                If the server returns an error.\n        \"\"\"\n\n        if privileged and utils.compare_version('1.19', self._version) < 0:\n            raise errors.InvalidVersion(\n                'Privileged exec is not supported in API < 1.19'\n            )\n        if user and utils.compare_version('1.19', self._version) < 0:\n            raise errors.InvalidVersion(\n                'User-specific exec is not supported in API < 1.19'\n            )\n        if isinstance(cmd, six.string_types):\n            cmd = utils.split_command(cmd)\n\n        data = {\n            'Container': container,\n            'User': user,\n            'Privileged': privileged,\n            'Tty': tty,\n            'AttachStdin': stdin,\n            'AttachStdout': stdout,\n            'AttachStderr': stderr,\n            'Cmd': cmd\n        }\n\n        url = self._url('/containers/{0}/exec', container)\n        res = self._post_json(url, data=data)\n        return self._result(res, True)\n\n    @utils.minimum_version('1.16')\n    def exec_inspect(self, exec_id):\n        \"\"\"\n        Return low-level information about an exec command.\n\n        Args:\n            exec_id (str): ID of the exec instance\n\n        Returns:\n            (dict): Dictionary of values returned by the endpoint.\n\n        Raises:\n            :py:class:`docker.errors.APIError`\n                If the server returns an error.\n        \"\"\"\n        if isinstance(exec_id, dict):\n            exec_id = exec_id.get('Id')\n        res = self._get(self._url(\"/exec/{0}/json\", exec_id))\n        return self._result(res, True)\n\n    @utils.minimum_version('1.15')\n    def exec_resize(self, exec_id, height=None, width=None):\n        \"\"\"\n        Resize the tty session used by the specified exec command.\n\n        Args:\n            exec_id (str): ID of the exec instance\n            height (int): Height of tty session\n            width (int): Width of tty session\n        \"\"\"\n\n        if isinstance(exec_id, dict):\n            exec_id = exec_id.get('Id')\n\n        params = {'h': height, 'w': width}\n        url = self._url(\"/exec/{0}/resize\", exec_id)\n        res = self._post(url, params=params)\n        self._raise_for_status(res)\n\n    @utils.minimum_version('1.15')\n    def exec_start(self, exec_id, detach=False, tty=False, stream=False,\n                   socket=False):\n        \"\"\"\n        Start a previously set up exec instance.\n\n        Args:\n            exec_id (str): ID of the exec instance\n            detach (bool): If true, detach from the exec command.\n                Default: False\n            tty (bool): Allocate a pseudo-TTY. Default: False\n            stream (bool): Stream response data. Default: False\n\n        Returns:\n            (generator or str): If ``stream=True``, a generator yielding\n            response chunks. A string containing response data otherwise.\n\n        Raises:\n            :py:class:`docker.errors.APIError`\n                If the server returns an error.\n        \"\"\"\n        # we want opened socket if socket == True\n        if isinstance(exec_id, dict):\n            exec_id = exec_id.get('Id')\n\n        data = {\n            'Tty': tty,\n            'Detach': detach\n        }\n\n        headers = {} if detach else {\n            'Connection': 'Upgrade',\n            'Upgrade': 'tcp'\n        }\n\n        res = self._post_json(\n            self._url('/exec/{0}/start', exec_id),\n            headers=headers,\n            data=data,\n            stream=True\n        )\n\n        if socket:\n            return self._get_raw_response_socket(res)\n        return self._read_from_socket(res, stream)\n", "path": "docker/api/exec_api.py"}], "after_files": [{"content": "import six\n\nfrom .. import errors\nfrom .. import utils\n\n\nclass ExecApiMixin(object):\n    @utils.minimum_version('1.15')\n    @utils.check_resource\n    def exec_create(self, container, cmd, stdout=True, stderr=True,\n                    stdin=False, tty=False, privileged=False, user=''):\n        \"\"\"\n        Sets up an exec instance in a running container.\n\n        Args:\n            container (str): Target container where exec instance will be\n                created\n            cmd (str or list): Command to be executed\n            stdout (bool): Attach to stdout. Default: ``True``\n            stderr (bool): Attach to stderr. Default: ``True``\n            stdin (bool): Attach to stdin. Default: ``False``\n            tty (bool): Allocate a pseudo-TTY. Default: False\n            privileged (bool): Run as privileged.\n            user (str): User to execute command as. Default: root\n\n        Returns:\n            (dict): A dictionary with an exec ``Id`` key.\n\n        Raises:\n            :py:class:`docker.errors.APIError`\n                If the server returns an error.\n        \"\"\"\n\n        if privileged and utils.compare_version('1.19', self._version) < 0:\n            raise errors.InvalidVersion(\n                'Privileged exec is not supported in API < 1.19'\n            )\n        if user and utils.compare_version('1.19', self._version) < 0:\n            raise errors.InvalidVersion(\n                'User-specific exec is not supported in API < 1.19'\n            )\n        if isinstance(cmd, six.string_types):\n            cmd = utils.split_command(cmd)\n\n        data = {\n            'Container': container,\n            'User': user,\n            'Privileged': privileged,\n            'Tty': tty,\n            'AttachStdin': stdin,\n            'AttachStdout': stdout,\n            'AttachStderr': stderr,\n            'Cmd': cmd\n        }\n\n        url = self._url('/containers/{0}/exec', container)\n        res = self._post_json(url, data=data)\n        return self._result(res, True)\n\n    @utils.minimum_version('1.16')\n    def exec_inspect(self, exec_id):\n        \"\"\"\n        Return low-level information about an exec command.\n\n        Args:\n            exec_id (str): ID of the exec instance\n\n        Returns:\n            (dict): Dictionary of values returned by the endpoint.\n\n        Raises:\n            :py:class:`docker.errors.APIError`\n                If the server returns an error.\n        \"\"\"\n        if isinstance(exec_id, dict):\n            exec_id = exec_id.get('Id')\n        res = self._get(self._url(\"/exec/{0}/json\", exec_id))\n        return self._result(res, True)\n\n    @utils.minimum_version('1.15')\n    def exec_resize(self, exec_id, height=None, width=None):\n        \"\"\"\n        Resize the tty session used by the specified exec command.\n\n        Args:\n            exec_id (str): ID of the exec instance\n            height (int): Height of tty session\n            width (int): Width of tty session\n        \"\"\"\n\n        if isinstance(exec_id, dict):\n            exec_id = exec_id.get('Id')\n\n        params = {'h': height, 'w': width}\n        url = self._url(\"/exec/{0}/resize\", exec_id)\n        res = self._post(url, params=params)\n        self._raise_for_status(res)\n\n    @utils.minimum_version('1.15')\n    def exec_start(self, exec_id, detach=False, tty=False, stream=False,\n                   socket=False):\n        \"\"\"\n        Start a previously set up exec instance.\n\n        Args:\n            exec_id (str): ID of the exec instance\n            detach (bool): If true, detach from the exec command.\n                Default: False\n            tty (bool): Allocate a pseudo-TTY. Default: False\n            stream (bool): Stream response data. Default: False\n\n        Returns:\n            (generator or str): If ``stream=True``, a generator yielding\n            response chunks. A string containing response data otherwise.\n\n        Raises:\n            :py:class:`docker.errors.APIError`\n                If the server returns an error.\n        \"\"\"\n        # we want opened socket if socket == True\n        if isinstance(exec_id, dict):\n            exec_id = exec_id.get('Id')\n\n        data = {\n            'Tty': tty,\n            'Detach': detach\n        }\n\n        headers = {} if detach else {\n            'Connection': 'Upgrade',\n            'Upgrade': 'tcp'\n        }\n\n        res = self._post_json(\n            self._url('/exec/{0}/start', exec_id),\n            headers=headers,\n            data=data,\n            stream=True\n        )\n        if detach:\n            return self._result(res)\n        if socket:\n            return self._get_raw_response_socket(res)\n        return self._read_from_socket(res, stream)\n", "path": "docker/api/exec_api.py"}]}