How does Python receive stdin and arguments differently?

南笙酒味 提交于 2019-12-14 03:05:48

问题


How exactly does Python receive

echo input | python script

and

python script input

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


回答1:


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

The command line args are passed automatically in the argv parameter as with any other c program. The main function for Python that is written in C (that is, 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.. */

While the contents of the pipe are stored in stdin which you can tap into via sys.stdin.

Using a sample test.py script:

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

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

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

Kewl!



来源:https://stackoverflow.com/questions/34782307/how-does-python-receive-stdin-and-arguments-differently

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!