Python 如何以不同方式接收标准输入和参数?

How does Python receive stdin and arguments differently?

Python究竟是如何接收

echo input | python script

python script input

不同?我知道一个通​​过标准输入,另一个作为参数传递,但后端发生了什么不同?

我不太确定是什么让您感到困惑。 stdin 和命令行参数被视为 two different things

由于您最有可能使用 CPython(Python 的 C 实现),因此命令行参数在 argv 参数中自动传递,与任何其他 c 程序。 CPython(位于python.c)的main函数接收它们:

int
main(int argc, char **argv)  // **argv <-- Your command line args
{
    wchar_t **argv_copy;   
    /* We need a second copy, as Python might modify the first one. */
    wchar_t **argv_copy2;
    /* ..rest of main omitted.. */

虽然管道的内容存储在 stdin 中,但您可以通过 sys.stdin 访问它。

使用示例 test.py 脚本:

import sys

print("Argv params:\n ", sys.argv)
if not sys.stdin.isatty():
    print("Command Line args: \n", sys.stdin.readlines())

运行 这没有管道执行产量:

(Python3)jim@jim: python test.py "hello world"
Argv params:
  ['test.py', 'hello world']

同时,使用 echo "Stdin up in here" | python test.py "hello world",我们将得到:

(Python3)jim@jim: echo "Stdin up in here" | python test.py "hello world"
Argv params:
 ['test.py', 'hello world']
Stdin: 
 ['Stdin up in here\n']

没有严格关系,但有趣的是:

此外,我记得您可以使用 Python 的 - 参数来执行存储在 stdin 中的内容:

(Python3)jimm@jim: echo "print('<stdin> input')" | python -
<stdin> input

邱尔!