使用Python Popen运行有多个输入的命令。

问题描述 投票:0回答:1

我想创建一个函数,当调用该函数时,会创建一个auth.json,以便与 twitter到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()

我对子进程不是很在行,所以我有点摸不着头脑。谁能帮我一把?

python subprocess popen
1个回答
0
投票

这取决于应用程序是如何编写的,但经常你可以只在一次写入中写下提示的答案 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")
© www.soinside.com 2019 - 2024. All rights reserved.