python接收输入参数_Python如何以不同方式接收stdin和参数?

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?

解决方案

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

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

{

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

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

input

Kewl!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值