【问题标题】:How to make python script type when prompted on shell在 shell 上提示时如何制作 python 脚本类型
【发布时间】:2020-11-02 06:35:06
【问题描述】:

类似的东西:How to make python script press 'enter' when prompted on Shell

就像那个问题,如果我有test_enter.py

print("press enter...")
input()
print("yay!")

还有这个文件:

from subprocess import Popen, PIPE
p = Popen(['python test_enter.py'], stdin=PIPE, shell=True)
p.communicate(input=b'\n')

但我希望它输入一些内容,然后按“回车”,而不只是换行。这可能吗?

【问题讨论】:

    标签: python linux


    【解决方案1】:

    要调用的脚本:

    print("write something here")
    inserted_string = input()
    print("You wrote: " + inserted_string)
    

    调用者脚本:

    from subprocess import Popen, PIPE
    import sys
    
    print("custom insert here...")
    inserted1 = input()
    
    if len(sys.argv) > 1:
      inserted2 = sys.argv[1]
    else:
      inserted2 = 'nothing here'
    
    p1 = Popen(['python script_to_call.py'], stdin=PIPE, shell=True)
    p1.communicate(input=b'standard string\n')
    
    print(" --- ")
    
    p2 = Popen(['python script_to_call.py'], stdin=PIPE, shell=True)
    p2.communicate(input=inserted1.encode('utf-8') + b'\n')
    
    print(" --- ")
    
    p3 = Popen(['python script_to_call.py'], stdin=PIPE, shell=True)
    p3.communicate(input=inserted2.encode('utf-8') + b'\n')
    

    运行命令

    python caller.py "string got from parameter"
    

    输出:

    custom insert here...
    string got from input
    
    write something here
    You wrote: standard string
     --- 
    write something here
    You wrote: string got from input
     --- 
    write something here
    You wrote: string got from parameter
    
    

    【讨论】:

    • 非常感谢。就像我想要的那样工作:)
    猜你喜欢
    • 2015-10-10
    • 1970-01-01
    • 2021-02-02
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    • 2016-03-19
    • 2015-11-25
    相关资源
    最近更新 更多