We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Warn users when they try to run Streamlit on an `ipynb` file.
# Problem

[Some users](https://discuss.streamlit.io/t/app-loading-problem/199/7?u=adrien_treuille) have tried to run Streamlit on a Jupyter notebook (`.ipnyb`) file and are confused when this doesn't work.

# Solution

It would be great if for _any_ non `.py` file, Streamlit behaved as follows:

```bash
$ streamlit run my_msft_word_file.docx

Error: Streamlit requires raw Python (.py) files, not .docx.
For more information, please see https://streamlit.io/docs

$ streamlit run my_notebook.ipnyb

Error: Streamlit requires raw Python (.py) files, not .ipnyb.
For more information, please see https://streamlit.io/docs
```



--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `lib/streamlit/cli.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 # Copyright 2018-2019 Streamlit Inc.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 #    http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 
16 """This is a script which is run when the Streamlit package is executed."""
17 
18 # Python 2/3 compatibility
19 from __future__ import print_function, division, absolute_import
20 
21 # Not importing unicode_literals from __future__ because click doesn't like it.
22 from streamlit.compatibility import setup_2_3_shims
23 
24 setup_2_3_shims(globals())
25 
26 from streamlit import config as _config
27 
28 import os
29 import click
30 
31 import streamlit
32 from streamlit.credentials import Credentials, check_credentials
33 from streamlit import version
34 import streamlit.bootstrap as bootstrap
35 from streamlit.case_converters import to_snake_case
36 
37 LOG_LEVELS = ["error", "warning", "info", "debug"]
38 
39 NEW_VERSION_TEXT = """
40   %(new_version)s
41 
42   See what's new at https://discuss.streamlit.io/c/announcements
43 
44   Enter the following command to upgrade:
45   %(prompt)s %(command)s
46 """ % {
47     "new_version": click.style(
48         "A new version of Streamlit is available.", fg="blue", bold=True
49     ),
50     "prompt": click.style("$", fg="blue"),
51     "command": click.style("pip install streamlit --upgrade", bold=True),
52 }
53 
54 
55 def _convert_config_option_to_click_option(config_option):
56     """Composes given config option options as options for click lib."""
57     option = "--{}".format(config_option.key)
58     param = config_option.key.replace(".", "_")
59     description = config_option.description
60     if config_option.deprecated:
61         description += "\n {} - {}".format(
62             config_option.deprecation_text, config_option.deprecation_date
63         )
64     envvar = "STREAMLIT_{}".format(to_snake_case(param).upper())
65 
66     return {
67         "param": param,
68         "description": description,
69         "type": config_option.type,
70         "option": option,
71         "envvar": envvar,
72     }
73 
74 
75 def configurator_options(func):
76     """Decorator that adds config param keys to click dynamically."""
77     for _, value in reversed(_config._config_options.items()):
78         parsed_parameter = _convert_config_option_to_click_option(value)
79         config_option = click.option(
80             parsed_parameter["option"],
81             parsed_parameter["param"],
82             help=parsed_parameter["description"],
83             type=parsed_parameter["type"],
84             show_envvar=True,
85             envvar=parsed_parameter["envvar"],
86         )
87         func = config_option(func)
88     return func
89 
90 
91 def _apply_config_options_from_cli(kwargs):
92     """The "streamlit run" command supports passing Streamlit's config options
93     as flags.
94 
95     This function reads through all config flags, massage them, and
96     pass them to _set_config() overriding default values and values set via
97     config.toml file
98 
99     """
100     for config_option in kwargs:
101         if kwargs[config_option] is not None:
102             config_option_def_key = config_option.replace("_", ".")
103 
104             _config._set_option(
105                 config_option_def_key,
106                 kwargs[config_option],
107                 "command-line argument or environment variable",
108             )
109 
110 
111 # Fetch remote file at url_path to script_path
112 def _download_remote(script_path, url_path):
113     import requests
114 
115     with open(script_path, "wb") as fp:
116         try:
117             resp = requests.get(url_path)
118             resp.raise_for_status()
119             fp.write(resp.content)
120         except requests.exceptions.RequestException as e:
121             raise click.BadParameter(("Unable to fetch {}.\n{}".format(url_path, e)))
122 
123 
124 @click.group(context_settings={"auto_envvar_prefix": "STREAMLIT"})
125 @click.option("--log_level", show_default=True, type=click.Choice(LOG_LEVELS))
126 @click.version_option(prog_name="Streamlit")
127 @click.pass_context
128 def main(ctx, log_level="info"):
129     """Try out a demo with:
130 
131         $ streamlit hello
132 
133     Or use the line below to run your own script:
134 
135         $ streamlit run your_script.py
136     """
137 
138     if log_level:
139         import streamlit.logger
140 
141         streamlit.logger.set_log_level(log_level.upper())
142 
143 
144 @main.command("help")
145 @click.pass_context
146 def help(ctx):
147     """Print this help message."""
148     # Pretend user typed 'streamlit --help' instead of 'streamlit help'.
149     import sys
150 
151     assert len(sys.argv) == 2  # This is always true, but let's assert anyway.
152     sys.argv[1] = "--help"
153     main()
154 
155 
156 @main.command("version")
157 @click.pass_context
158 def main_version(ctx):
159     """Print Streamlit's version number."""
160     # Pretend user typed 'streamlit --version' instead of 'streamlit version'
161     import sys
162 
163     assert len(sys.argv) == 2  # This is always true, but let's assert anyway.
164     sys.argv[1] = "--version"
165     main()
166 
167 
168 @main.command("docs")
169 def main_docs():
170     """Show help in browser."""
171     print("Showing help page in browser...")
172     from streamlit import util
173 
174     util.open_browser("https://streamlit.io/docs")
175 
176 
177 @main.command("hello")
178 @configurator_options
179 def main_hello(**kwargs):
180     """Runs the Hello World script."""
181     from streamlit.hello import hello
182 
183     _apply_config_options_from_cli(kwargs)
184 
185     filename = hello.__file__
186 
187     # For Python 2 when Streamlit is actually installed (make install rather
188     # than make develop).
189     if filename.endswith(".pyc"):
190         filename = "%s.py" % filename[:-4]
191 
192     _main_run(filename)
193 
194 
195 @main.command("run")
196 @configurator_options
197 @click.argument("target", required=True, envvar="STREAMLIT_RUN_TARGET")
198 @click.argument("args", nargs=-1)
199 def main_run(target, args=None, **kwargs):
200     """Run a Python script, piping stderr to Streamlit.
201 
202     The script can be local or it can be an url. In the latter case, Streamlit
203     will download the script to a temporary file and runs this file.
204 
205     """
206     from validators import url
207 
208     _apply_config_options_from_cli(kwargs)
209 
210     if url(target):
211         from streamlit.temporary_directory import TemporaryDirectory
212 
213         with TemporaryDirectory() as temp_dir:
214             from urllib.parse import urlparse
215             from streamlit import url_util
216 
217             path = urlparse(target).path
218             script_path = os.path.join(temp_dir, path.strip("/").rsplit("/", 1)[-1])
219             # if this is a GitHub/Gist blob url, convert to a raw URL first.
220             target = url_util.process_gitblob_url(target)
221             _download_remote(script_path, target)
222             _main_run(script_path, args)
223     else:
224         if not os.path.exists(target):
225             raise click.BadParameter("File does not exist: {}".format(target))
226         _main_run(target, args)
227 
228 
229 # Utility function to compute the command line as a string
230 def _get_command_line_as_string():
231     import subprocess
232 
233     cmd_line_as_list = [click.get_current_context().parent.command_path]
234     cmd_line_as_list.extend(click.get_os_args())
235     return subprocess.list2cmdline(cmd_line_as_list)
236 
237 
238 def _main_run(file, args=[]):
239     command_line = _get_command_line_as_string()
240 
241     # Set a global flag indicating that we're "within" streamlit.
242     streamlit._is_running_with_streamlit = True
243 
244     # Check credentials.
245     check_credentials()
246 
247     # Notify if streamlit is out of date.
248     if version.should_show_new_version_notice():
249         click.echo(NEW_VERSION_TEXT)
250 
251     bootstrap.run(file, command_line, args)
252 
253 
254 # DEPRECATED
255 
256 # TODO: Remove after 2019-09-01
257 @main.command("clear_cache", deprecated=True, hidden=True)
258 @click.pass_context
259 def main_clear_cache(ctx):
260     """Deprecated."""
261     click.echo(click.style('Use "cache clear" instead.', fg="red"))
262     ctx.invoke(cache_clear)
263 
264 
265 # TODO: Remove after 2019-09-01
266 @main.command("show_config", deprecated=True, hidden=True)
267 @click.pass_context
268 def main_show_config(ctx):
269     """Deprecated."""
270     click.echo(click.style('Use "config show" instead.', fg="red"))
271     ctx.invoke(config_show)
272 
273 
274 # SUBCOMMAND: cache
275 
276 
277 @main.group("cache")
278 def cache():
279     """Manage the Streamlit cache."""
280     pass
281 
282 
283 @cache.command("clear")
284 def cache_clear():
285     """Clear the Streamlit on-disk cache."""
286     import streamlit.caching
287 
288     result = streamlit.caching.clear_cache()
289     cache_path = streamlit.caching.get_cache_path()
290     if result:
291         print("Cleared directory %s." % cache_path)
292     else:
293         print("Nothing to clear at %s." % cache_path)
294 
295 
296 # SUBCOMMAND: config
297 
298 
299 @main.group("config")
300 def config():
301     """Manage Streamlit's config settings."""
302     pass
303 
304 
305 @config.command("show")
306 @configurator_options
307 def config_show(**kwargs):
308     """Show all of Streamlit's config settings."""
309 
310     _apply_config_options_from_cli(kwargs)
311 
312     _config.show_config()
313 
314 
315 # SUBCOMMAND: activate
316 
317 
318 @main.group("activate", invoke_without_command=True)
319 @click.pass_context
320 def activate(ctx):
321     """Activate Streamlit by entering your email."""
322     if not ctx.invoked_subcommand:
323         Credentials.get_current().activate()
324 
325 
326 @activate.command("reset")
327 def activate_reset():
328     """Reset Activation Credentials."""
329     Credentials.get_current().reset()
330 
331 
332 if __name__ == "__main__":
333     main()
334
```
--- 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/lib/streamlit/cli.py b/lib/streamlit/cli.py
--- a/lib/streamlit/cli.py
+++ b/lib/streamlit/cli.py
@@ -34,7 +34,9 @@
 import streamlit.bootstrap as bootstrap
 from streamlit.case_converters import to_snake_case
 
-LOG_LEVELS = ["error", "warning", "info", "debug"]
+ACCEPTED_FILE_EXTENSIONS = ("py", "py3")
+
+LOG_LEVELS = ("error", "warning", "info", "debug")
 
 NEW_VERSION_TEXT = """
   %(new_version)s
@@ -207,6 +209,10 @@
 
     _apply_config_options_from_cli(kwargs)
 
+    _, extension = os.path.splitext(target)
+    if extension[1:] not in ACCEPTED_FILE_EXTENSIONS:
+        raise click.BadArgumentUsage("Streamlit requires raw Python (.py) files, not %s.\nFor more information, please see https://streamlit.io/docs" % extension)
+
     if url(target):
         from streamlit.temporary_directory import TemporaryDirectory

{"golden_diff": "diff --git a/lib/streamlit/cli.py b/lib/streamlit/cli.py\n--- a/lib/streamlit/cli.py\n+++ b/lib/streamlit/cli.py\n@@ -34,7 +34,9 @@\n import streamlit.bootstrap as bootstrap\n from streamlit.case_converters import to_snake_case\n \n-LOG_LEVELS = [\"error\", \"warning\", \"info\", \"debug\"]\n+ACCEPTED_FILE_EXTENSIONS = (\"py\", \"py3\")\n+\n+LOG_LEVELS = (\"error\", \"warning\", \"info\", \"debug\")\n \n NEW_VERSION_TEXT = \"\"\"\n   %(new_version)s\n@@ -207,6 +209,10 @@\n \n     _apply_config_options_from_cli(kwargs)\n \n+    _, extension = os.path.splitext(target)\n+    if extension[1:] not in ACCEPTED_FILE_EXTENSIONS:\n+        raise click.BadArgumentUsage(\"Streamlit requires raw Python (.py) files, not %s.\\nFor more information, please see https://streamlit.io/docs\" % extension)\n+\n     if url(target):\n         from streamlit.temporary_directory import TemporaryDirectory\n", "issue": "Warn users when they try to run Streamlit on an `ipynb` file.\n# Problem\r\n\r\n[Some users](https://discuss.streamlit.io/t/app-loading-problem/199/7?u=adrien_treuille) have tried to run Streamlit on a Jupyter notebook (`.ipnyb`) file and are confused when this doesn't work.\r\n\r\n# Solution\r\n\r\nIt would be great if for _any_ non `.py` file, Streamlit behaved as follows:\r\n\r\n```bash\r\n$ streamlit run my_msft_word_file.docx\r\n\r\nError: Streamlit requires raw Python (.py) files, not .docx.\r\nFor more information, please see https://streamlit.io/docs\r\n\r\n$ streamlit run my_notebook.ipnyb\r\n\r\nError: Streamlit requires raw Python (.py) files, not .ipnyb.\r\nFor more information, please see https://streamlit.io/docs\r\n```\r\n\r\n\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n# Copyright 2018-2019 Streamlit Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"This is a script which is run when the Streamlit package is executed.\"\"\"\n\n# Python 2/3 compatibility\nfrom __future__ import print_function, division, absolute_import\n\n# Not importing unicode_literals from __future__ because click doesn't like it.\nfrom streamlit.compatibility import setup_2_3_shims\n\nsetup_2_3_shims(globals())\n\nfrom streamlit import config as _config\n\nimport os\nimport click\n\nimport streamlit\nfrom streamlit.credentials import Credentials, check_credentials\nfrom streamlit import version\nimport streamlit.bootstrap as bootstrap\nfrom streamlit.case_converters import to_snake_case\n\nLOG_LEVELS = [\"error\", \"warning\", \"info\", \"debug\"]\n\nNEW_VERSION_TEXT = \"\"\"\n  %(new_version)s\n\n  See what's new at https://discuss.streamlit.io/c/announcements\n\n  Enter the following command to upgrade:\n  %(prompt)s %(command)s\n\"\"\" % {\n    \"new_version\": click.style(\n        \"A new version of Streamlit is available.\", fg=\"blue\", bold=True\n    ),\n    \"prompt\": click.style(\"$\", fg=\"blue\"),\n    \"command\": click.style(\"pip install streamlit --upgrade\", bold=True),\n}\n\n\ndef _convert_config_option_to_click_option(config_option):\n    \"\"\"Composes given config option options as options for click lib.\"\"\"\n    option = \"--{}\".format(config_option.key)\n    param = config_option.key.replace(\".\", \"_\")\n    description = config_option.description\n    if config_option.deprecated:\n        description += \"\\n {} - {}\".format(\n            config_option.deprecation_text, config_option.deprecation_date\n        )\n    envvar = \"STREAMLIT_{}\".format(to_snake_case(param).upper())\n\n    return {\n        \"param\": param,\n        \"description\": description,\n        \"type\": config_option.type,\n        \"option\": option,\n        \"envvar\": envvar,\n    }\n\n\ndef configurator_options(func):\n    \"\"\"Decorator that adds config param keys to click dynamically.\"\"\"\n    for _, value in reversed(_config._config_options.items()):\n        parsed_parameter = _convert_config_option_to_click_option(value)\n        config_option = click.option(\n            parsed_parameter[\"option\"],\n            parsed_parameter[\"param\"],\n            help=parsed_parameter[\"description\"],\n            type=parsed_parameter[\"type\"],\n            show_envvar=True,\n            envvar=parsed_parameter[\"envvar\"],\n        )\n        func = config_option(func)\n    return func\n\n\ndef _apply_config_options_from_cli(kwargs):\n    \"\"\"The \"streamlit run\" command supports passing Streamlit's config options\n    as flags.\n\n    This function reads through all config flags, massage them, and\n    pass them to _set_config() overriding default values and values set via\n    config.toml file\n\n    \"\"\"\n    for config_option in kwargs:\n        if kwargs[config_option] is not None:\n            config_option_def_key = config_option.replace(\"_\", \".\")\n\n            _config._set_option(\n                config_option_def_key,\n                kwargs[config_option],\n                \"command-line argument or environment variable\",\n            )\n\n\n# Fetch remote file at url_path to script_path\ndef _download_remote(script_path, url_path):\n    import requests\n\n    with open(script_path, \"wb\") as fp:\n        try:\n            resp = requests.get(url_path)\n            resp.raise_for_status()\n            fp.write(resp.content)\n        except requests.exceptions.RequestException as e:\n            raise click.BadParameter((\"Unable to fetch {}.\\n{}\".format(url_path, e)))\n\n\n@click.group(context_settings={\"auto_envvar_prefix\": \"STREAMLIT\"})\n@click.option(\"--log_level\", show_default=True, type=click.Choice(LOG_LEVELS))\n@click.version_option(prog_name=\"Streamlit\")\n@click.pass_context\ndef main(ctx, log_level=\"info\"):\n    \"\"\"Try out a demo with:\n\n        $ streamlit hello\n\n    Or use the line below to run your own script:\n\n        $ streamlit run your_script.py\n    \"\"\"\n\n    if log_level:\n        import streamlit.logger\n\n        streamlit.logger.set_log_level(log_level.upper())\n\n\n@main.command(\"help\")\n@click.pass_context\ndef help(ctx):\n    \"\"\"Print this help message.\"\"\"\n    # Pretend user typed 'streamlit --help' instead of 'streamlit help'.\n    import sys\n\n    assert len(sys.argv) == 2  # This is always true, but let's assert anyway.\n    sys.argv[1] = \"--help\"\n    main()\n\n\n@main.command(\"version\")\n@click.pass_context\ndef main_version(ctx):\n    \"\"\"Print Streamlit's version number.\"\"\"\n    # Pretend user typed 'streamlit --version' instead of 'streamlit version'\n    import sys\n\n    assert len(sys.argv) == 2  # This is always true, but let's assert anyway.\n    sys.argv[1] = \"--version\"\n    main()\n\n\n@main.command(\"docs\")\ndef main_docs():\n    \"\"\"Show help in browser.\"\"\"\n    print(\"Showing help page in browser...\")\n    from streamlit import util\n\n    util.open_browser(\"https://streamlit.io/docs\")\n\n\n@main.command(\"hello\")\n@configurator_options\ndef main_hello(**kwargs):\n    \"\"\"Runs the Hello World script.\"\"\"\n    from streamlit.hello import hello\n\n    _apply_config_options_from_cli(kwargs)\n\n    filename = hello.__file__\n\n    # For Python 2 when Streamlit is actually installed (make install rather\n    # than make develop).\n    if filename.endswith(\".pyc\"):\n        filename = \"%s.py\" % filename[:-4]\n\n    _main_run(filename)\n\n\n@main.command(\"run\")\n@configurator_options\n@click.argument(\"target\", required=True, envvar=\"STREAMLIT_RUN_TARGET\")\n@click.argument(\"args\", nargs=-1)\ndef main_run(target, args=None, **kwargs):\n    \"\"\"Run a Python script, piping stderr to Streamlit.\n\n    The script can be local or it can be an url. In the latter case, Streamlit\n    will download the script to a temporary file and runs this file.\n\n    \"\"\"\n    from validators import url\n\n    _apply_config_options_from_cli(kwargs)\n\n    if url(target):\n        from streamlit.temporary_directory import TemporaryDirectory\n\n        with TemporaryDirectory() as temp_dir:\n            from urllib.parse import urlparse\n            from streamlit import url_util\n\n            path = urlparse(target).path\n            script_path = os.path.join(temp_dir, path.strip(\"/\").rsplit(\"/\", 1)[-1])\n            # if this is a GitHub/Gist blob url, convert to a raw URL first.\n            target = url_util.process_gitblob_url(target)\n            _download_remote(script_path, target)\n            _main_run(script_path, args)\n    else:\n        if not os.path.exists(target):\n            raise click.BadParameter(\"File does not exist: {}\".format(target))\n        _main_run(target, args)\n\n\n# Utility function to compute the command line as a string\ndef _get_command_line_as_string():\n    import subprocess\n\n    cmd_line_as_list = [click.get_current_context().parent.command_path]\n    cmd_line_as_list.extend(click.get_os_args())\n    return subprocess.list2cmdline(cmd_line_as_list)\n\n\ndef _main_run(file, args=[]):\n    command_line = _get_command_line_as_string()\n\n    # Set a global flag indicating that we're \"within\" streamlit.\n    streamlit._is_running_with_streamlit = True\n\n    # Check credentials.\n    check_credentials()\n\n    # Notify if streamlit is out of date.\n    if version.should_show_new_version_notice():\n        click.echo(NEW_VERSION_TEXT)\n\n    bootstrap.run(file, command_line, args)\n\n\n# DEPRECATED\n\n# TODO: Remove after 2019-09-01\n@main.command(\"clear_cache\", deprecated=True, hidden=True)\n@click.pass_context\ndef main_clear_cache(ctx):\n    \"\"\"Deprecated.\"\"\"\n    click.echo(click.style('Use \"cache clear\" instead.', fg=\"red\"))\n    ctx.invoke(cache_clear)\n\n\n# TODO: Remove after 2019-09-01\n@main.command(\"show_config\", deprecated=True, hidden=True)\n@click.pass_context\ndef main_show_config(ctx):\n    \"\"\"Deprecated.\"\"\"\n    click.echo(click.style('Use \"config show\" instead.', fg=\"red\"))\n    ctx.invoke(config_show)\n\n\n# SUBCOMMAND: cache\n\n\n@main.group(\"cache\")\ndef cache():\n    \"\"\"Manage the Streamlit cache.\"\"\"\n    pass\n\n\n@cache.command(\"clear\")\ndef cache_clear():\n    \"\"\"Clear the Streamlit on-disk cache.\"\"\"\n    import streamlit.caching\n\n    result = streamlit.caching.clear_cache()\n    cache_path = streamlit.caching.get_cache_path()\n    if result:\n        print(\"Cleared directory %s.\" % cache_path)\n    else:\n        print(\"Nothing to clear at %s.\" % cache_path)\n\n\n# SUBCOMMAND: config\n\n\n@main.group(\"config\")\ndef config():\n    \"\"\"Manage Streamlit's config settings.\"\"\"\n    pass\n\n\n@config.command(\"show\")\n@configurator_options\ndef config_show(**kwargs):\n    \"\"\"Show all of Streamlit's config settings.\"\"\"\n\n    _apply_config_options_from_cli(kwargs)\n\n    _config.show_config()\n\n\n# SUBCOMMAND: activate\n\n\n@main.group(\"activate\", invoke_without_command=True)\n@click.pass_context\ndef activate(ctx):\n    \"\"\"Activate Streamlit by entering your email.\"\"\"\n    if not ctx.invoked_subcommand:\n        Credentials.get_current().activate()\n\n\n@activate.command(\"reset\")\ndef activate_reset():\n    \"\"\"Reset Activation Credentials.\"\"\"\n    Credentials.get_current().reset()\n\n\nif __name__ == \"__main__\":\n    main()\n", "path": "lib/streamlit/cli.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n# Copyright 2018-2019 Streamlit Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"This is a script which is run when the Streamlit package is executed.\"\"\"\n\n# Python 2/3 compatibility\nfrom __future__ import print_function, division, absolute_import\n\n# Not importing unicode_literals from __future__ because click doesn't like it.\nfrom streamlit.compatibility import setup_2_3_shims\n\nsetup_2_3_shims(globals())\n\nfrom streamlit import config as _config\n\nimport os\nimport click\n\nimport streamlit\nfrom streamlit.credentials import Credentials, check_credentials\nfrom streamlit import version\nimport streamlit.bootstrap as bootstrap\nfrom streamlit.case_converters import to_snake_case\n\nACCEPTED_FILE_EXTENSIONS = (\"py\", \"py3\")\n\nLOG_LEVELS = (\"error\", \"warning\", \"info\", \"debug\")\n\nNEW_VERSION_TEXT = \"\"\"\n  %(new_version)s\n\n  See what's new at https://discuss.streamlit.io/c/announcements\n\n  Enter the following command to upgrade:\n  %(prompt)s %(command)s\n\"\"\" % {\n    \"new_version\": click.style(\n        \"A new version of Streamlit is available.\", fg=\"blue\", bold=True\n    ),\n    \"prompt\": click.style(\"$\", fg=\"blue\"),\n    \"command\": click.style(\"pip install streamlit --upgrade\", bold=True),\n}\n\n\ndef _convert_config_option_to_click_option(config_option):\n    \"\"\"Composes given config option options as options for click lib.\"\"\"\n    option = \"--{}\".format(config_option.key)\n    param = config_option.key.replace(\".\", \"_\")\n    description = config_option.description\n    if config_option.deprecated:\n        description += \"\\n {} - {}\".format(\n            config_option.deprecation_text, config_option.deprecation_date\n        )\n    envvar = \"STREAMLIT_{}\".format(to_snake_case(param).upper())\n\n    return {\n        \"param\": param,\n        \"description\": description,\n        \"type\": config_option.type,\n        \"option\": option,\n        \"envvar\": envvar,\n    }\n\n\ndef configurator_options(func):\n    \"\"\"Decorator that adds config param keys to click dynamically.\"\"\"\n    for _, value in reversed(_config._config_options.items()):\n        parsed_parameter = _convert_config_option_to_click_option(value)\n        config_option = click.option(\n            parsed_parameter[\"option\"],\n            parsed_parameter[\"param\"],\n            help=parsed_parameter[\"description\"],\n            type=parsed_parameter[\"type\"],\n            show_envvar=True,\n            envvar=parsed_parameter[\"envvar\"],\n        )\n        func = config_option(func)\n    return func\n\n\ndef _apply_config_options_from_cli(kwargs):\n    \"\"\"The \"streamlit run\" command supports passing Streamlit's config options\n    as flags.\n\n    This function reads through all config flags, massage them, and\n    pass them to _set_config() overriding default values and values set via\n    config.toml file\n\n    \"\"\"\n    for config_option in kwargs:\n        if kwargs[config_option] is not None:\n            config_option_def_key = config_option.replace(\"_\", \".\")\n\n            _config._set_option(\n                config_option_def_key,\n                kwargs[config_option],\n                \"command-line argument or environment variable\",\n            )\n\n\n# Fetch remote file at url_path to script_path\ndef _download_remote(script_path, url_path):\n    import requests\n\n    with open(script_path, \"wb\") as fp:\n        try:\n            resp = requests.get(url_path)\n            resp.raise_for_status()\n            fp.write(resp.content)\n        except requests.exceptions.RequestException as e:\n            raise click.BadParameter((\"Unable to fetch {}.\\n{}\".format(url_path, e)))\n\n\n@click.group(context_settings={\"auto_envvar_prefix\": \"STREAMLIT\"})\n@click.option(\"--log_level\", show_default=True, type=click.Choice(LOG_LEVELS))\n@click.version_option(prog_name=\"Streamlit\")\n@click.pass_context\ndef main(ctx, log_level=\"info\"):\n    \"\"\"Try out a demo with:\n\n        $ streamlit hello\n\n    Or use the line below to run your own script:\n\n        $ streamlit run your_script.py\n    \"\"\"\n\n    if log_level:\n        import streamlit.logger\n\n        streamlit.logger.set_log_level(log_level.upper())\n\n\n@main.command(\"help\")\n@click.pass_context\ndef help(ctx):\n    \"\"\"Print this help message.\"\"\"\n    # Pretend user typed 'streamlit --help' instead of 'streamlit help'.\n    import sys\n\n    assert len(sys.argv) == 2  # This is always true, but let's assert anyway.\n    sys.argv[1] = \"--help\"\n    main()\n\n\n@main.command(\"version\")\n@click.pass_context\ndef main_version(ctx):\n    \"\"\"Print Streamlit's version number.\"\"\"\n    # Pretend user typed 'streamlit --version' instead of 'streamlit version'\n    import sys\n\n    assert len(sys.argv) == 2  # This is always true, but let's assert anyway.\n    sys.argv[1] = \"--version\"\n    main()\n\n\n@main.command(\"docs\")\ndef main_docs():\n    \"\"\"Show help in browser.\"\"\"\n    print(\"Showing help page in browser...\")\n    from streamlit import util\n\n    util.open_browser(\"https://streamlit.io/docs\")\n\n\n@main.command(\"hello\")\n@configurator_options\ndef main_hello(**kwargs):\n    \"\"\"Runs the Hello World script.\"\"\"\n    from streamlit.hello import hello\n\n    _apply_config_options_from_cli(kwargs)\n\n    filename = hello.__file__\n\n    # For Python 2 when Streamlit is actually installed (make install rather\n    # than make develop).\n    if filename.endswith(\".pyc\"):\n        filename = \"%s.py\" % filename[:-4]\n\n    _main_run(filename)\n\n\n@main.command(\"run\")\n@configurator_options\n@click.argument(\"target\", required=True, envvar=\"STREAMLIT_RUN_TARGET\")\n@click.argument(\"args\", nargs=-1)\ndef main_run(target, args=None, **kwargs):\n    \"\"\"Run a Python script, piping stderr to Streamlit.\n\n    The script can be local or it can be an url. In the latter case, Streamlit\n    will download the script to a temporary file and runs this file.\n\n    \"\"\"\n    from validators import url\n\n    _apply_config_options_from_cli(kwargs)\n\n    _, extension = os.path.splitext(target)\n    if extension[1:] not in ACCEPTED_FILE_EXTENSIONS:\n        raise click.BadArgumentUsage(\"Streamlit requires raw Python (.py) files, not %s.\\nFor more information, please see https://streamlit.io/docs\" % extension)\n\n    if url(target):\n        from streamlit.temporary_directory import TemporaryDirectory\n\n        with TemporaryDirectory() as temp_dir:\n            from urllib.parse import urlparse\n            from streamlit import url_util\n\n            path = urlparse(target).path\n            script_path = os.path.join(temp_dir, path.strip(\"/\").rsplit(\"/\", 1)[-1])\n            # if this is a GitHub/Gist blob url, convert to a raw URL first.\n            target = url_util.process_gitblob_url(target)\n            _download_remote(script_path, target)\n            _main_run(script_path, args)\n    else:\n        if not os.path.exists(target):\n            raise click.BadParameter(\"File does not exist: {}\".format(target))\n        _main_run(target, args)\n\n\n# Utility function to compute the command line as a string\ndef _get_command_line_as_string():\n    import subprocess\n\n    cmd_line_as_list = [click.get_current_context().parent.command_path]\n    cmd_line_as_list.extend(click.get_os_args())\n    return subprocess.list2cmdline(cmd_line_as_list)\n\n\ndef _main_run(file, args=[]):\n    command_line = _get_command_line_as_string()\n\n    # Set a global flag indicating that we're \"within\" streamlit.\n    streamlit._is_running_with_streamlit = True\n\n    # Check credentials.\n    check_credentials()\n\n    # Notify if streamlit is out of date.\n    if version.should_show_new_version_notice():\n        click.echo(NEW_VERSION_TEXT)\n\n    bootstrap.run(file, command_line, args)\n\n\n# DEPRECATED\n\n# TODO: Remove after 2019-09-01\n@main.command(\"clear_cache\", deprecated=True, hidden=True)\n@click.pass_context\ndef main_clear_cache(ctx):\n    \"\"\"Deprecated.\"\"\"\n    click.echo(click.style('Use \"cache clear\" instead.', fg=\"red\"))\n    ctx.invoke(cache_clear)\n\n\n# TODO: Remove after 2019-09-01\n@main.command(\"show_config\", deprecated=True, hidden=True)\n@click.pass_context\ndef main_show_config(ctx):\n    \"\"\"Deprecated.\"\"\"\n    click.echo(click.style('Use \"config show\" instead.', fg=\"red\"))\n    ctx.invoke(config_show)\n\n\n# SUBCOMMAND: cache\n\n\n@main.group(\"cache\")\ndef cache():\n    \"\"\"Manage the Streamlit cache.\"\"\"\n    pass\n\n\n@cache.command(\"clear\")\ndef cache_clear():\n    \"\"\"Clear the Streamlit on-disk cache.\"\"\"\n    import streamlit.caching\n\n    result = streamlit.caching.clear_cache()\n    cache_path = streamlit.caching.get_cache_path()\n    if result:\n        print(\"Cleared directory %s.\" % cache_path)\n    else:\n        print(\"Nothing to clear at %s.\" % cache_path)\n\n\n# SUBCOMMAND: config\n\n\n@main.group(\"config\")\ndef config():\n    \"\"\"Manage Streamlit's config settings.\"\"\"\n    pass\n\n\n@config.command(\"show\")\n@configurator_options\ndef config_show(**kwargs):\n    \"\"\"Show all of Streamlit's config settings.\"\"\"\n\n    _apply_config_options_from_cli(kwargs)\n\n    _config.show_config()\n\n\n# SUBCOMMAND: activate\n\n\n@main.group(\"activate\", invoke_without_command=True)\n@click.pass_context\ndef activate(ctx):\n    \"\"\"Activate Streamlit by entering your email.\"\"\"\n    if not ctx.invoked_subcommand:\n        Credentials.get_current().activate()\n\n\n@activate.command(\"reset\")\ndef activate_reset():\n    \"\"\"Reset Activation Credentials.\"\"\"\n    Credentials.get_current().reset()\n\n\nif __name__ == \"__main__\":\n    main()\n", "path": "lib/streamlit/cli.py"}]}