[英]How can I give a user input into terminal after running a terminal command in python?
I have a python script that runs a command in terminal using the subprocess module and this command runs another script that asks for a user input.我有一个 python 脚本,它使用 subprocess 模块在终端中运行一个命令,这个命令运行另一个脚本,要求用户输入。 How can I give a user input to terminal from my original python script?如何从我的原始 python 脚本向终端提供用户输入?
Example:例子:
contents of introduction.sh below introduction.sh 下面的内容
#!/bin/bash
**# Ask the user for their name**
echo Hello, who am I talking to?
read varname
echo It\'s nice to meet you $varname
running introduction.sh would output the following:运行 introduction.sh 将 output 以下内容:
user@bash ./introduction.sh
Hello, who am I talking to?
Ryan
It's nice to meet you Ryan
My python script runs introduction.sh in terminal perfectly fine.我的 python 脚本在终端中完美运行 introduction.sh。 What I can't figure out how to do is to run introduction.sh with a name such as Ryan as a user input all from my python script.我不知道该怎么做是运行 introduction.sh 并使用诸如 Ryan 之类的名称作为用户输入,所有这些都来自我的 python 脚本。
I tried using the os module to call introduction.sh and then using os again to give the user input as two separate lines.我尝试使用 os 模块调用 introduction.sh,然后再次使用 os 将用户输入分为两行。 This strategy runs introduction.sh perfectly fine but treats my second input as an undefined variable and does nothing.该策略运行 introduction.sh 非常好,但将我的第二个输入视为未定义的变量并且不执行任何操作。
My current script testing.py is below.我当前的脚本 testing.py 在下面。
import subprocess
subprocess.run(["python3", "testing.py"], shell=True, capture_output=True) subprocess.run(["python3", "testing.py"], shell=True, capture_output=True)
subprocess.run(["Ryan"], shell=True, capture_output=True) subprocess.run(["Ryan"], shell=True, capture_output=True)
print('done')打印('完成')
There are a number of ways of doing this with the subprocess
package. Here's a simple way to do so:有多种方法可以使用subprocess
进程 package 执行此操作。这是一种简单的方法:
import subprocess
process = subprocess.Popen('/tmp/introduction.sh', stdin=subprocess.PIPE)
process.communicate("George".encode())
Result:结果:
Hello, who am I talking to?
It's nice to meet you George
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.