Python 如何在脚本中读取stdin?

Python 如何在脚本中读取stdin?,python,stdin,Python,Stdin,什么也没发生 我应该如何在自定义输入上运行自己的代码?这看起来应该很简单,但我在文档中没有看到如何做到这一点的示例。我相信您可能想要或想要更多您可以选择的功能 scratch.py$ python3 scratch.py -h usage: scratch.py [-h] n positional arguments: n Example help text here. optional arguments: -h, --help show this help

什么也没发生


我应该如何在自定义输入上运行自己的代码?这看起来应该很简单,但我在文档中没有看到如何做到这一点的示例。

我相信您可能想要或想要更多您可以选择的功能

scratch.py$ python3 scratch.py -h
usage: scratch.py [-h] n

positional arguments:
  n           Example help text here.

optional arguments:
  -h, --help  show this help message and exit
使用
sys.argv的示例

(ykp) y9@Y9Acer:~/practice$ python optimal_summands.py 15
if __name__ == '__main__':
    filename = sys.argv[0]
    passed_args = map(int, sys.argv[1:]) # if you're expecting all args to be int.
    # python3 module.py 1 2 3
    # passed_args = [1, 2, 3]
使用
argparse的示例

(ykp) y9@Y9Acer:~/practice$ python optimal_summands.py 15
if __name__ == '__main__':
    filename = sys.argv[0]
    passed_args = map(int, sys.argv[1:]) # if you're expecting all args to be int.
    # python3 module.py 1 2 3
    # passed_args = [1, 2, 3]
您也可以使用
argparse
为用户提供帮助,如下所示:

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("n", type=int, help="Example help text here.")

    args = parser.parse_args()
    n = args.n
    print(isinstance(n, int)) # true
以上不包括导入语句
import sys
import argparse
argparse
中的可选参数以双连字符作为前缀,如
python
文档所示

scratch.py$ python3 scratch.py -h
usage: scratch.py [-h] n

positional arguments:
  n           Example help text here.

optional arguments:
  -h, --help  show this help message and exit

如果您只是希望通过CLI进行输入;您可以选择使用
input\u val=input('Question here')

15
是一个命令行参数,而不是标准输入。
15
在您的示例中不在
stdin
中,而是在
argv
中。“什么也没发生”可能是一个程序在等待您的输入。您还没有为进程的标准输入提供任何内容,因此
sys.stdin.read()
将挂起,等待来自stdinRelated的EOF-那么如果我不能使用终端输入,stdin有什么意义呢?我如何向stdin提供数据?谢谢。那么,有没有一种方法可以让我使用
sys.stdin.read()
来做类似的事情呢?或者不,不我的朋友,请阅读一下。因此,似乎要使用sys.stdin.read(),我必须在运行
python\u summands.py
之后输入参数,然后执行CTRL+D(在Linux中)对于EOF,通常
sys.stdin.read
用于使用类似
python3 script.py
的东西从文件中读取数据-这是我过去提出的唯一需要的用例。尽管您可能希望使用类似以下内容:
input('Number of summand your'd choose'))
这将要求用户在CLI中输入数字。这非常有用。我在网上其他任何地方都找不到这个解释,这让我很震惊。