Python如何以不同的方式接收stdin和参数?

2024-07-03 06:14:32 发布

您现在位置:Python中文网/ 问答频道 /正文

Python究竟是如何接收的

echo input | python script

以及

^{pr2}$

不一样吗?我知道一个通过stdin,另一个作为参数传递,但是在后端会发生什么不同的情况呢?在


Tags: echoinputstdinscript情况pr2端会
1条回答
网友
1楼 · 发布于 2024-07-03 06:14:32

我不太清楚是什么让你困惑。stdin和命令行参数被视为two different things。在

命令行参数在argv参数中自动传递,就像任何其他c程序一样。用C(即,^{})编写的Python主函数接收它们:

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脚本:

^{pr2}$

在不进行管道铺设的情况下运行该管道会产生:

(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

基尔!在

相关问题 更多 >