Python 如何以不同的方式接收标准输入和参数? [英] How does Python receive stdin and arguments differently?

查看:17
本文介绍了Python 如何以不同的方式接收标准输入和参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python究竟是如何接收的

How exactly does Python receive

echo input | python script

python script input

不一样?我知道一个通​​过 stdin 传入,另一个作为参数传递,但后端有什么不同?

differently? I know that one comes through stdin and the other is passed as an argument, but what happens differently in the back-end?

推荐答案

我不太确定是什么让您感到困惑.stdin 和命令行参数被视为 两种不同的事物.

I'm not exactly sure what is confusing you here. stdin and command line arguments are treated as two different things.

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

Since you're most likely using CPython (the C implementation of Python) the command line args are passed automatically in the argv parameter as with any other c program. The main function for CPython (located in python.c) receives them:

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 访问它.

While the contents of the pipe are stored in stdin which you can tap into via 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())

在不执行管道的情况下运行此代码:

Running this with no piping performed yields:

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

虽然,使用 echo "Stdin up in here" |python test.py "hello world",我们会得到:

While, using echo "Stdin up in here" | python test.py "hello world", we'll get:

(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 参数:

Additionally, I remembered that you can execute content that is stored in stdin by using the - argument for Python:

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

Kewl!

这篇关于Python 如何以不同的方式接收标准输入和参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆