We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
qtile top breaks when the terminal is too small
I just launched `qtile top` several times but it only worked once, and broke on the next runs:

```
$ qtile top --force-start
$ qtile top
Traceback (most recent call last):
  File "libqtile/scripts/main.py", line 46, in main
    options.func(options)
  File "qtile/libqtile/scripts/top.py", line 158, in top
    force_start=force_start)
  File "/usr/lib/python3.7/curses/__init__.py", line 102, in wrapper
    return func(stdscr, *args, **kwds)
  File "libqtile/scripts/top.py", line 95, in get_stats
    scr.addstr(cnt + 1, 0, '{:<3} {:<40} {:<30}'.format(index, filename, mem))
_curses.error: addwstr() returned ERR
```

Also I'm not sure what's happening, but I can't replicate this in another X session, whether I use PYTHONTRACEMALLOC or --force-start.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `libqtile/scripts/top.py`
Content:
```
1 # Copyright (c) 2015, Roger Duran
2 #
3 # Permission is hereby granted, free of charge, to any person obtaining a copy
4 # of this software and associated documentation files (the "Software"), to deal
5 # in the Software without restriction, including without limitation the rights
6 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 # copies of the Software, and to permit persons to whom the Software is
8 # furnished to do so, subject to the following conditions:
9 #
10 # The above copyright notice and this permission notice shall be included in
11 # all copies or substantial portions of the Software.
12 #
13 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19 # SOFTWARE.
20 
21 """
22     Command-line top like for qtile
23 """
24 
25 import curses
26 import linecache
27 import os
28 import time
29 
30 from libqtile import command_client, command_interface, ipc
31 
32 """ These imports are here because they are not supported in pypy
33 having them at the top of the file causes problems when running any
34 of the other scripts.
35 """
36 try:
37     import tracemalloc
38     from tracemalloc import Snapshot
39     ENABLED = True
40 except ModuleNotFoundError:
41     ENABLED = False
42 
43 
44 class TraceNotStarted(Exception):
45     pass
46 
47 
48 class TraceCantStart(Exception):
49     pass
50 
51 
52 def get_trace(client, force_start):
53     (started, path) = client.tracemalloc_dump()
54     if force_start and not started:
55         client.tracemalloc_toggle()
56         (started, path) = client.tracemalloc_dump()
57         if not started:
58             raise TraceCantStart
59     elif not started:
60         raise TraceNotStarted
61 
62     return Snapshot.load(path)
63 
64 
65 def filter_snapshot(snapshot):
66     return snapshot.filter_traces((
67         tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
68         tracemalloc.Filter(False, "<unknown>"),
69     ))
70 
71 
72 def get_stats(scr, client, group_by='lineno', limit=10, seconds=1.5,
73               force_start=False):
74     (max_y, max_x) = scr.getmaxyx()
75     curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
76     while True:
77         scr.addstr(0, 0, "Qtile - Top {} lines".format(limit))
78         scr.addstr(1, 0, '{0:<3s} {1:<40s} {2:<30s} {3:<16s}'.format('#', 'Line', 'Memory', ' ' * (max_x - 71)),
79                    curses.A_BOLD | curses.A_REVERSE)
80 
81         snapshot = get_trace(client, force_start)
82         snapshot = filter_snapshot(snapshot)
83         top_stats = snapshot.statistics(group_by)
84         cnt = 1
85         for index, stat in enumerate(top_stats[:limit], 1):
86             frame = stat.traceback[0]
87             # replace "/path/to/module/file.py" with "module/file.py"
88             filename = os.sep.join(frame.filename.split(os.sep)[-2:])
89             code = ""
90             line = linecache.getline(frame.filename, frame.lineno).strip()
91             if line:
92                 code = line
93             mem = "{:.1f} KiB".format(stat.size / 1024.0)
94             filename = "{}:{}".format(filename, frame.lineno)
95             scr.addstr(cnt + 1, 0, '{:<3} {:<40} {:<30}'.format(index, filename, mem))
96             scr.addstr(cnt + 2, 4, code, curses.color_pair(1))
97             cnt += 2
98 
99         other = top_stats[limit:]
100         cnt += 2
101         if other:
102             size = sum(stat.size for stat in other)
103             other_size = ("{:d} other: {:.1f} KiB".format(len(other), size / 1024.0))
104             scr.addstr(cnt, 0, other_size, curses.A_BOLD)
105             cnt += 1
106 
107         total = sum(stat.size for stat in top_stats)
108         total_size = "Total allocated size: {0:.1f} KiB".format(total / 1024.0)
109         scr.addstr(cnt, 0, total_size, curses.A_BOLD)
110 
111         scr.move(max_y - 2, max_y - 2)
112         scr.refresh()
113         time.sleep(seconds)
114         scr.erase()
115 
116 
117 def raw_stats(client, group_by='lineno', limit=10, force_start=False):
118     snapshot = get_trace(client, force_start)
119     snapshot = filter_snapshot(snapshot)
120     top_stats = snapshot.statistics(group_by)
121 
122     print("Qtile - Top {} lines".format(limit))
123     for index, stat in enumerate(top_stats[:limit], 1):
124         frame = stat.traceback[0]
125         # replace "/path/to/module/file.py" with "module/file.py"
126         filename = os.sep.join(frame.filename.split(os.sep)[-2:])
127         print("#{}: {}:{}: {:.1f} KiB"
128               .format(index, filename, frame.lineno, stat.size / 1024.0))
129         line = linecache.getline(frame.filename, frame.lineno).strip()
130         if line:
131             print('    {}'.format(line))
132 
133     other = top_stats[limit:]
134     if other:
135         size = sum(stat.size for stat in other)
136         print("{:d} other: {:.1f} KiB".format(len(other), size / 1024.0))
137     total = sum(stat.size for stat in top_stats)
138     print("Total allocated size: {0:.1f} KiB".format(total / 1024.0))
139 
140 
141 def top(opts):
142     if not ENABLED:
143         raise Exception('Could not import tracemalloc')
144     lines = opts.lines
145     seconds = opts.seconds
146     force_start = opts.force_start
147     if opts.socket is None:
148         socket = ipc.find_sockfile()
149     else:
150         socket = opts.socket
151     client = ipc.Client(socket)
152     client = command_interface.IPCCommandInterface(client)
153     client = command_client.InteractiveCommandClient(client)
154 
155     try:
156         if not opts.raw:
157             curses.wrapper(get_stats, client, limit=lines, seconds=seconds,
158                            force_start=force_start)
159         else:
160             raw_stats(client, limit=lines, force_start=force_start)
161     except TraceNotStarted:
162         print("tracemalloc not started on qtile, start by setting "
163               "PYTHONTRACEMALLOC=1 before starting qtile")
164         print("or force start tracemalloc now, but you'll lose early traces")
165         exit(1)
166     except TraceCantStart:
167         print("Can't start tracemalloc on qtile, check the logs")
168     except KeyboardInterrupt:
169         exit(-1)
170 
171 
172 def add_subcommand(subparsers):
173     parser = subparsers.add_parser("top", help="resource usage information")
174     parser.add_argument('-l', '--lines', type=int, dest="lines", default=10,
175                         help='Number of lines.')
176     parser.add_argument('-r', '--raw', dest="raw", action="store_true",
177                         default=False, help='Output raw without curses')
178     parser.add_argument('-t', '--time', type=float, dest="seconds",
179                         default=1.5, help='Number of seconds to refresh')
180     parser.add_argument('--force-start', dest="force_start",
181                         action="store_true", default=False,
182                         help='Force start tracemalloc on qtile')
183     parser.add_argument('-s', '--socket', type=str, dest="socket",
184                         help='Use specified communication socket.')
185     parser.set_defaults(func=top)
186
```
--- 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/libqtile/scripts/top.py b/libqtile/scripts/top.py
--- a/libqtile/scripts/top.py
+++ b/libqtile/scripts/top.py
@@ -167,6 +167,9 @@
         print("Can't start tracemalloc on qtile, check the logs")
     except KeyboardInterrupt:
         exit(-1)
+    except curses.error:
+        print("Terminal too small for curses interface.")
+        raw_stats(client, limit=lines, force_start=force_start)
 
 
 def add_subcommand(subparsers):

{"golden_diff": "diff --git a/libqtile/scripts/top.py b/libqtile/scripts/top.py\n--- a/libqtile/scripts/top.py\n+++ b/libqtile/scripts/top.py\n@@ -167,6 +167,9 @@\n         print(\"Can't start tracemalloc on qtile, check the logs\")\n     except KeyboardInterrupt:\n         exit(-1)\n+    except curses.error:\n+        print(\"Terminal too small for curses interface.\")\n+        raw_stats(client, limit=lines, force_start=force_start)\n \n \n def add_subcommand(subparsers):\n", "issue": "qtile top breaks when the terminal is too small\nI just launched `qtile top` several times but it only worked once, and broke on the next runs:\r\n\r\n```\r\n$ qtile top --force-start\r\n$ qtile top\r\nTraceback (most recent call last):\r\n  File \"libqtile/scripts/main.py\", line 46, in main\r\n    options.func(options)\r\n  File \"qtile/libqtile/scripts/top.py\", line 158, in top\r\n    force_start=force_start)\r\n  File \"/usr/lib/python3.7/curses/__init__.py\", line 102, in wrapper\r\n    return func(stdscr, *args, **kwds)\r\n  File \"libqtile/scripts/top.py\", line 95, in get_stats\r\n    scr.addstr(cnt + 1, 0, '{:<3} {:<40} {:<30}'.format(index, filename, mem))\r\n_curses.error: addwstr() returned ERR\r\n```\r\n\r\nAlso I'm not sure what's happening, but I can't replicate this in another X session, whether I use PYTHONTRACEMALLOC or --force-start.\n", "before_files": [{"content": "# Copyright (c) 2015, Roger Duran\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\"\"\"\n    Command-line top like for qtile\n\"\"\"\n\nimport curses\nimport linecache\nimport os\nimport time\n\nfrom libqtile import command_client, command_interface, ipc\n\n\"\"\" These imports are here because they are not supported in pypy\nhaving them at the top of the file causes problems when running any\nof the other scripts.\n\"\"\"\ntry:\n    import tracemalloc\n    from tracemalloc import Snapshot\n    ENABLED = True\nexcept ModuleNotFoundError:\n    ENABLED = False\n\n\nclass TraceNotStarted(Exception):\n    pass\n\n\nclass TraceCantStart(Exception):\n    pass\n\n\ndef get_trace(client, force_start):\n    (started, path) = client.tracemalloc_dump()\n    if force_start and not started:\n        client.tracemalloc_toggle()\n        (started, path) = client.tracemalloc_dump()\n        if not started:\n            raise TraceCantStart\n    elif not started:\n        raise TraceNotStarted\n\n    return Snapshot.load(path)\n\n\ndef filter_snapshot(snapshot):\n    return snapshot.filter_traces((\n        tracemalloc.Filter(False, \"<frozen importlib._bootstrap>\"),\n        tracemalloc.Filter(False, \"<unknown>\"),\n    ))\n\n\ndef get_stats(scr, client, group_by='lineno', limit=10, seconds=1.5,\n              force_start=False):\n    (max_y, max_x) = scr.getmaxyx()\n    curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)\n    while True:\n        scr.addstr(0, 0, \"Qtile - Top {} lines\".format(limit))\n        scr.addstr(1, 0, '{0:<3s} {1:<40s} {2:<30s} {3:<16s}'.format('#', 'Line', 'Memory', ' ' * (max_x - 71)),\n                   curses.A_BOLD | curses.A_REVERSE)\n\n        snapshot = get_trace(client, force_start)\n        snapshot = filter_snapshot(snapshot)\n        top_stats = snapshot.statistics(group_by)\n        cnt = 1\n        for index, stat in enumerate(top_stats[:limit], 1):\n            frame = stat.traceback[0]\n            # replace \"/path/to/module/file.py\" with \"module/file.py\"\n            filename = os.sep.join(frame.filename.split(os.sep)[-2:])\n            code = \"\"\n            line = linecache.getline(frame.filename, frame.lineno).strip()\n            if line:\n                code = line\n            mem = \"{:.1f} KiB\".format(stat.size / 1024.0)\n            filename = \"{}:{}\".format(filename, frame.lineno)\n            scr.addstr(cnt + 1, 0, '{:<3} {:<40} {:<30}'.format(index, filename, mem))\n            scr.addstr(cnt + 2, 4, code, curses.color_pair(1))\n            cnt += 2\n\n        other = top_stats[limit:]\n        cnt += 2\n        if other:\n            size = sum(stat.size for stat in other)\n            other_size = (\"{:d} other: {:.1f} KiB\".format(len(other), size / 1024.0))\n            scr.addstr(cnt, 0, other_size, curses.A_BOLD)\n            cnt += 1\n\n        total = sum(stat.size for stat in top_stats)\n        total_size = \"Total allocated size: {0:.1f} KiB\".format(total / 1024.0)\n        scr.addstr(cnt, 0, total_size, curses.A_BOLD)\n\n        scr.move(max_y - 2, max_y - 2)\n        scr.refresh()\n        time.sleep(seconds)\n        scr.erase()\n\n\ndef raw_stats(client, group_by='lineno', limit=10, force_start=False):\n    snapshot = get_trace(client, force_start)\n    snapshot = filter_snapshot(snapshot)\n    top_stats = snapshot.statistics(group_by)\n\n    print(\"Qtile - Top {} lines\".format(limit))\n    for index, stat in enumerate(top_stats[:limit], 1):\n        frame = stat.traceback[0]\n        # replace \"/path/to/module/file.py\" with \"module/file.py\"\n        filename = os.sep.join(frame.filename.split(os.sep)[-2:])\n        print(\"#{}: {}:{}: {:.1f} KiB\"\n              .format(index, filename, frame.lineno, stat.size / 1024.0))\n        line = linecache.getline(frame.filename, frame.lineno).strip()\n        if line:\n            print('    {}'.format(line))\n\n    other = top_stats[limit:]\n    if other:\n        size = sum(stat.size for stat in other)\n        print(\"{:d} other: {:.1f} KiB\".format(len(other), size / 1024.0))\n    total = sum(stat.size for stat in top_stats)\n    print(\"Total allocated size: {0:.1f} KiB\".format(total / 1024.0))\n\n\ndef top(opts):\n    if not ENABLED:\n        raise Exception('Could not import tracemalloc')\n    lines = opts.lines\n    seconds = opts.seconds\n    force_start = opts.force_start\n    if opts.socket is None:\n        socket = ipc.find_sockfile()\n    else:\n        socket = opts.socket\n    client = ipc.Client(socket)\n    client = command_interface.IPCCommandInterface(client)\n    client = command_client.InteractiveCommandClient(client)\n\n    try:\n        if not opts.raw:\n            curses.wrapper(get_stats, client, limit=lines, seconds=seconds,\n                           force_start=force_start)\n        else:\n            raw_stats(client, limit=lines, force_start=force_start)\n    except TraceNotStarted:\n        print(\"tracemalloc not started on qtile, start by setting \"\n              \"PYTHONTRACEMALLOC=1 before starting qtile\")\n        print(\"or force start tracemalloc now, but you'll lose early traces\")\n        exit(1)\n    except TraceCantStart:\n        print(\"Can't start tracemalloc on qtile, check the logs\")\n    except KeyboardInterrupt:\n        exit(-1)\n\n\ndef add_subcommand(subparsers):\n    parser = subparsers.add_parser(\"top\", help=\"resource usage information\")\n    parser.add_argument('-l', '--lines', type=int, dest=\"lines\", default=10,\n                        help='Number of lines.')\n    parser.add_argument('-r', '--raw', dest=\"raw\", action=\"store_true\",\n                        default=False, help='Output raw without curses')\n    parser.add_argument('-t', '--time', type=float, dest=\"seconds\",\n                        default=1.5, help='Number of seconds to refresh')\n    parser.add_argument('--force-start', dest=\"force_start\",\n                        action=\"store_true\", default=False,\n                        help='Force start tracemalloc on qtile')\n    parser.add_argument('-s', '--socket', type=str, dest=\"socket\",\n                        help='Use specified communication socket.')\n    parser.set_defaults(func=top)\n", "path": "libqtile/scripts/top.py"}], "after_files": [{"content": "# Copyright (c) 2015, Roger Duran\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\"\"\"\n    Command-line top like for qtile\n\"\"\"\n\nimport curses\nimport linecache\nimport os\nimport time\n\nfrom libqtile import command_client, command_interface, ipc\n\n\"\"\" These imports are here because they are not supported in pypy\nhaving them at the top of the file causes problems when running any\nof the other scripts.\n\"\"\"\ntry:\n    import tracemalloc\n    from tracemalloc import Snapshot\n    ENABLED = True\nexcept ModuleNotFoundError:\n    ENABLED = False\n\n\nclass TraceNotStarted(Exception):\n    pass\n\n\nclass TraceCantStart(Exception):\n    pass\n\n\ndef get_trace(client, force_start):\n    (started, path) = client.tracemalloc_dump()\n    if force_start and not started:\n        client.tracemalloc_toggle()\n        (started, path) = client.tracemalloc_dump()\n        if not started:\n            raise TraceCantStart\n    elif not started:\n        raise TraceNotStarted\n\n    return Snapshot.load(path)\n\n\ndef filter_snapshot(snapshot):\n    return snapshot.filter_traces((\n        tracemalloc.Filter(False, \"<frozen importlib._bootstrap>\"),\n        tracemalloc.Filter(False, \"<unknown>\"),\n    ))\n\n\ndef get_stats(scr, client, group_by='lineno', limit=10, seconds=1.5,\n              force_start=False):\n    (max_y, max_x) = scr.getmaxyx()\n    curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)\n    while True:\n        scr.addstr(0, 0, \"Qtile - Top {} lines\".format(limit))\n        scr.addstr(1, 0, '{0:<3s} {1:<40s} {2:<30s} {3:<16s}'.format('#', 'Line', 'Memory', ' ' * (max_x - 71)),\n                   curses.A_BOLD | curses.A_REVERSE)\n\n        snapshot = get_trace(client, force_start)\n        snapshot = filter_snapshot(snapshot)\n        top_stats = snapshot.statistics(group_by)\n        cnt = 1\n        for index, stat in enumerate(top_stats[:limit], 1):\n            frame = stat.traceback[0]\n            # replace \"/path/to/module/file.py\" with \"module/file.py\"\n            filename = os.sep.join(frame.filename.split(os.sep)[-2:])\n            code = \"\"\n            line = linecache.getline(frame.filename, frame.lineno).strip()\n            if line:\n                code = line\n            mem = \"{:.1f} KiB\".format(stat.size / 1024.0)\n            filename = \"{}:{}\".format(filename, frame.lineno)\n            scr.addstr(cnt + 1, 0, '{:<3} {:<40} {:<30}'.format(index, filename, mem))\n            scr.addstr(cnt + 2, 4, code, curses.color_pair(1))\n            cnt += 2\n\n        other = top_stats[limit:]\n        cnt += 2\n        if other:\n            size = sum(stat.size for stat in other)\n            other_size = (\"{:d} other: {:.1f} KiB\".format(len(other), size / 1024.0))\n            scr.addstr(cnt, 0, other_size, curses.A_BOLD)\n            cnt += 1\n\n        total = sum(stat.size for stat in top_stats)\n        total_size = \"Total allocated size: {0:.1f} KiB\".format(total / 1024.0)\n        scr.addstr(cnt, 0, total_size, curses.A_BOLD)\n\n        scr.move(max_y - 2, max_y - 2)\n        scr.refresh()\n        time.sleep(seconds)\n        scr.erase()\n\n\ndef raw_stats(client, group_by='lineno', limit=10, force_start=False):\n    snapshot = get_trace(client, force_start)\n    snapshot = filter_snapshot(snapshot)\n    top_stats = snapshot.statistics(group_by)\n\n    print(\"Qtile - Top {} lines\".format(limit))\n    for index, stat in enumerate(top_stats[:limit], 1):\n        frame = stat.traceback[0]\n        # replace \"/path/to/module/file.py\" with \"module/file.py\"\n        filename = os.sep.join(frame.filename.split(os.sep)[-2:])\n        print(\"#{}: {}:{}: {:.1f} KiB\"\n              .format(index, filename, frame.lineno, stat.size / 1024.0))\n        line = linecache.getline(frame.filename, frame.lineno).strip()\n        if line:\n            print('    {}'.format(line))\n\n    other = top_stats[limit:]\n    if other:\n        size = sum(stat.size for stat in other)\n        print(\"{:d} other: {:.1f} KiB\".format(len(other), size / 1024.0))\n    total = sum(stat.size for stat in top_stats)\n    print(\"Total allocated size: {0:.1f} KiB\".format(total / 1024.0))\n\n\ndef top(opts):\n    if not ENABLED:\n        raise Exception('Could not import tracemalloc')\n    lines = opts.lines\n    seconds = opts.seconds\n    force_start = opts.force_start\n    if opts.socket is None:\n        socket = ipc.find_sockfile()\n    else:\n        socket = opts.socket\n    client = ipc.Client(socket)\n    client = command_interface.IPCCommandInterface(client)\n    client = command_client.InteractiveCommandClient(client)\n\n    try:\n        if not opts.raw:\n            curses.wrapper(get_stats, client, limit=lines, seconds=seconds,\n                           force_start=force_start)\n        else:\n            raw_stats(client, limit=lines, force_start=force_start)\n    except TraceNotStarted:\n        print(\"tracemalloc not started on qtile, start by setting \"\n              \"PYTHONTRACEMALLOC=1 before starting qtile\")\n        print(\"or force start tracemalloc now, but you'll lose early traces\")\n        exit(1)\n    except TraceCantStart:\n        print(\"Can't start tracemalloc on qtile, check the logs\")\n    except KeyboardInterrupt:\n        exit(-1)\n    except curses.error:\n        print(\"Terminal too small for curses interface.\")\n        raw_stats(client, limit=lines, force_start=force_start)\n\n\ndef add_subcommand(subparsers):\n    parser = subparsers.add_parser(\"top\", help=\"resource usage information\")\n    parser.add_argument('-l', '--lines', type=int, dest=\"lines\", default=10,\n                        help='Number of lines.')\n    parser.add_argument('-r', '--raw', dest=\"raw\", action=\"store_true\",\n                        default=False, help='Output raw without curses')\n    parser.add_argument('-t', '--time', type=float, dest=\"seconds\",\n                        default=1.5, help='Number of seconds to refresh')\n    parser.add_argument('--force-start', dest=\"force_start\",\n                        action=\"store_true\", default=False,\n                        help='Force start tracemalloc on qtile')\n    parser.add_argument('-s', '--socket', type=str, dest=\"socket\",\n                        help='Use specified communication socket.')\n    parser.set_defaults(func=top)\n", "path": "libqtile/scripts/top.py"}]}