Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python如何以不同的方式接收stdin和参数?_Python_Arguments_Stdin - Fatal编程技术网

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

Python如何以不同的方式接收stdin和参数?,python,arguments,stdin,Python,Arguments,Stdin,Python究竟是如何接收数据的 echo input | python script 及 不同?我知道一个是通过stdin传递的,另一个是作为参数传递的,但是在后端会发生什么不同呢?我不太确定是什么让您感到困惑stdin和命令行参数被视为 由于您最有可能使用的是CPython(Python的C实现),因此命令行args会像其他任何C程序一样在argv参数中自动传递。CPython的main功能(位于)接收它们: int main(int argc, char **argv) // **ar

Python究竟是如何接收数据的

echo input | python script


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

我不太确定是什么让您感到困惑
stdin
和命令行参数被视为


由于您最有可能使用的是CPython(Python的C实现),因此命令行args会像其他任何
C
程序一样在
argv
参数中自动传递。CPython的
main
功能(位于)接收它们:

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.. */
在不执行管道操作的情况下运行此操作将产生:

(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
(蟒蛇3)jimm@jim:echo“print('input')”| python-
输入

凯尔

如果没有使用
sys.argv[1]
作为输入,那么
python脚本输入是否真的有效?好的,让我们测试一下。
script
的内容是
print(input())
echo'foobar'| python脚本
是否只是打印输出,而不是要求您输入?而且,
python脚本“foobar”
是否也打印了
foobar
,并且没有运行
input()
?另外,请尝试打印(\uuuu import\uuuu('sys').argv[1])
,并检查输出结果。奇怪的结果。对于第一个,它立即返回一个错误,对于第二个,它运行输入,然后抛出一个错误。对于最后一个,我想你是指.argv[0]?不要管它的argv[1]对不起,但是python.c是什么?CPython的
main
函数,记住,
python
是用
c
语言编写的。好吧,我只是不知道stdin和cmd参数的处理方式完全不同,谢谢!谢谢你的回答,吉姆。虽然其他答案指出stdin和argv并不等同,但你的答案是我发现的第一个能解释为什么会这样的答案。
(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']
(Python3)jimm@jim: echo "print('<stdin> input')" | python -
<stdin> input