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

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

问题描述

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"时,我们将得到:

(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']


不是严格相关,但有趣的注释:


Not strictly related, but an interesting note:

此外,我还记得您可以使用

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

基尔!

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

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