We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
When "streamlit run" file doesn't exit and has no extension, error printout is weird
1. Create a Python file and call it `example` (without .py)
2. `streamlit run example`

Here's what you get:
<img width="400px" src="https://user-images.githubusercontent.com/690814/95294472-307bcb00-082a-11eb-86b0-37c2a1335988.png" />

**This error message is not a valid sentence: "Streamlit requires raw Python (.py) files, not ."**

What's happening is that the code is trying to write the file extension in the error message, but in this case the file has no extension.

We should instead say something like "Streamlit requires raw Python (.py) files, and the provided file has no extension."



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