繁体   English   中英

使用 Python 使用多个输入打开运行命令

[英]Using Python Popen to run command with mulitple inputs

我想创建一个 function ,当调用它时,会创建一个 auth.json 用于twitter-to-sqlite 为此,function 必须在终端中运行命令,然后在弹出时输入 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 (在 linux tty )。 在您的情况下,这听起来像是 write 作品,所以使用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")

暂无
暂无

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

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