简体   繁体   English

Python 默认如何读取命令行 arguments

[英]Python how to read command line arguments by default

I'm using Python with the command prompt and but I want to change the default setting for command line arguments to program read from stdin.我在命令提示符下使用 Python,但我想更改命令行 arguments 的默认设置以从标准输入读取程序。 I can have it this way by using the '-' before command line arguments but I want it to be read from stdin by default, so that the command line arguments appear in sys.argv without the '-'.我可以通过在命令行 arguments 之前使用“-”来实现这种方式,但我希望默认情况下从标准输入读取它,以便命令行 arguments 出现在没有“-”的 sys.argv 中。 How can I do this?我怎样才能做到这一点?

If I understood your question write you can do the following:如果我理解您的问题,您可以执行以下操作:

create master.py file:创建 master.py 文件:

import subprocess as sp

if __name__ == "__main__":
    subprocess = sp.Popen(["python", "child.py"], stdin=sp.PIPE)
    # pay attention stdin=sp.PIPE, otherwise you would not be able to send data to child subprocess
    subprocess.communicate("Hi There\nDear Friend\nBye".encode('utf8')) # we send data here

create child.py - it will be started from master process master.py创建 child.py - 它将从主进程 master.py 启动

import sys

if __name__ == "__main__":
    for line in sys.stdin.read().split("\n"):  # read data from master process
        print(line + "!!!")

Start master process.启动主进程。 You are supposed to get: Hi There!!!你应该得到:你好!!! Dear Friend!!!亲爱的朋友!!! Bye!!!再见!!!

I hope it was helpful answer, if not please let me know.我希望这是有用的答案,如果没有,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM