Secret Recipes of the Python Ninja
上QQ阅读APP看书,第一时间看更新

Interface options

When called with no options, the Python interpreter starts in interactive mode. In this mode, the interpreter monitors the command line for Python commands and executes them as they are entered.

To exit, an EOF (end-of-file) character is entered; in *NIX operating systems, this is Ctl-D and Ctl-Z on Windows (normally, the EOF character is automatically provided when reading from a file but, as this is not the case in interactive mode, the user must provide it).

The options in this section can be combined with miscellaneous options, which are as follows:

  • -c <"command">: Entering this option causes Python to execute the entered command. The command can be one or more statements, separated by new lines, and with normal Python whitespace considerations. The quotations (single or double) must be included and surround all the statements that make up the command.
  • -m <module>: This option causes Python to search sys.path for the indicated module and then execute its contents as the __main__ module. Modules executed via this method do not require the .py extension. In addition, a package of modules can be provided; in this case, Python will execute the <pkg>.__main__ as the __main__ module.
    This option cannot be used with any compiled C modules, including built-in modules, as they are not Python code. However, .pyc pre-compiled Python files can use this option, even if the original source code files are not available, as they are pure Python code.
    When this option is invoked, any code that is below the if __name__ == "__main__" line will be executed. This is a good place to put self-testing or configuration code.
  • <script>: This option causes the Python code in the indicated script to be executed. The script provided must have a filesystem path (absolute or relative) that points to a regular Python file, a directory containing a __main__.py file, or a zipped file with a __main__.py file.
  • -: An empty dash option tells the interpreter to read from standard input (sys.stdin); if the standard input is connected to a Terminal, then normal interactive mode is started. While a keyboard is the default input device, sys.stdin actually accepts any File object, so anything from the user's keyboard to a file can be used as the input method. Hence, any sort of file can be used as input, ranging from a normal text file to a CSV file.