使用 Python Popen to 运行 命令与多个输入
Using Python Popen to run command with mulitple inputs
我想创建一个函数,调用时会创建一个 auth.json 供 twitter-to-sqlite 使用。为此,函数必须在终端中 运行 命令,然后在弹出时输入 API 密钥、API 秘密、访问令牌和访问令牌秘密:
$ twitter-to-sqlite auth
API Key: <Input API Ky>
API Secret: <Input API Secret>
Access Token: <Input Access Token>
Access Token Secret: <Input Access Token Secret>
这是我目前所拥有的,但显然不起作用:
from os import getenv
from subprocess import PIPE, Popen
from time import sleep
# API key:
api_key = getenv("API_KEY")
# API secret key:
api_secret = getenv("API_SECRET")
# Access token:
access_token = getenv("ACCESS_TOKEN")
# Access token secret:
access_token_secret = getenv("ACCESS_TOKEN_SECRET")
def create_auth_json():
#Create auth.json file for twitter-to-sqlite
p = Popen(['twitter-to-sqlite', 'auth'], stdin=PIPE)
sleep(2)
print(api_key)
sleep(2)
print(api_secret)
sleep(2)
print(access_token)
sleep(2)
print(access_token_secret)
if __name__ == "__main__":
create_auth_json()
我不太擅长子流程,所以我有点难过。任何人都可以伸出援手吗?
这取决于应用程序的编写方式,但通常您只需将提示的答案一次性写到 stdin
。有时程序会根据 stdin
类型更改其行为,而您必须设置 tty
(在 linux 上)。在你的情况下,这听起来像是写作作品,所以使用 communicate
来写作并关闭 stdin
.
def create_auth_json():
#Create auth.json file for twitter-to-sqlite
p = Popen(['twitter-to-sqlite', 'auth'], stdin=PIPE)
p.communicate(
f"{api_key}\n{api_secret}\n{access_token}\n{access_token_secret}\n")
我想创建一个函数,调用时会创建一个 auth.json 供 twitter-to-sqlite 使用。为此,函数必须在终端中 运行 命令,然后在弹出时输入 API 密钥、API 秘密、访问令牌和访问令牌秘密:
$ twitter-to-sqlite auth
API Key: <Input API Ky>
API Secret: <Input API Secret>
Access Token: <Input Access Token>
Access Token Secret: <Input Access Token Secret>
这是我目前所拥有的,但显然不起作用:
from os import getenv
from subprocess import PIPE, Popen
from time import sleep
# API key:
api_key = getenv("API_KEY")
# API secret key:
api_secret = getenv("API_SECRET")
# Access token:
access_token = getenv("ACCESS_TOKEN")
# Access token secret:
access_token_secret = getenv("ACCESS_TOKEN_SECRET")
def create_auth_json():
#Create auth.json file for twitter-to-sqlite
p = Popen(['twitter-to-sqlite', 'auth'], stdin=PIPE)
sleep(2)
print(api_key)
sleep(2)
print(api_secret)
sleep(2)
print(access_token)
sleep(2)
print(access_token_secret)
if __name__ == "__main__":
create_auth_json()
我不太擅长子流程,所以我有点难过。任何人都可以伸出援手吗?
这取决于应用程序的编写方式,但通常您只需将提示的答案一次性写到 stdin
。有时程序会根据 stdin
类型更改其行为,而您必须设置 tty
(在 linux 上)。在你的情况下,这听起来像是写作作品,所以使用 communicate
来写作并关闭 stdin
.
def create_auth_json():
#Create auth.json file for twitter-to-sqlite
p = Popen(['twitter-to-sqlite', 'auth'], stdin=PIPE)
p.communicate(
f"{api_key}\n{api_secret}\n{access_token}\n{access_token_secret}\n")