![](/img/trans.png)
[英]How can I ask for user input in python through the terminal in windows?
[英]How can I give a user input into terminal after running a terminal command in python?
我有一個 python 腳本,它使用 subprocess 模塊在終端中運行一個命令,這個命令運行另一個腳本,要求用戶輸入。 如何從我的原始 python 腳本向終端提供用戶輸入?
例子:
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
運行 introduction.sh 將 output 以下內容:
user@bash ./introduction.sh
Hello, who am I talking to?
Ryan
It's nice to meet you Ryan
我的 python 腳本在終端中完美運行 introduction.sh。 我不知道該怎么做是運行 introduction.sh 並使用諸如 Ryan 之類的名稱作為用戶輸入,所有這些都來自我的 python 腳本。
我嘗試使用 os 模塊調用 introduction.sh,然后再次使用 os 將用戶輸入分為兩行。 該策略運行 introduction.sh 非常好,但將我的第二個輸入視為未定義的變量並且不執行任何操作。
我當前的腳本 testing.py 在下面。
import subprocess
subprocess.run(["python3", "testing.py"], shell=True, capture_output=True)
subprocess.run(["Ryan"], shell=True, capture_output=True)
打印('完成')
有多種方法可以使用subprocess
進程 package 執行此操作。這是一種簡單的方法:
import subprocess
process = subprocess.Popen('/tmp/introduction.sh', stdin=subprocess.PIPE)
process.communicate("George".encode())
結果:
Hello, who am I talking to?
It's nice to meet you George
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.