Search code examples
pythonsubprocesspopen

Using Python Popen to run command with mulitple inputs


I want to create a function that, when called, creates an auth.json for use with twitter-to-sqlite. To do so, the function has to run a command in the terminal, then input the API key, API secret, access token, and access token secret as they pop up:

$ 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>

Here is what I have so far, which clearly isn't working:

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()

I'm not very good with subprocess, so I'm kind of stumped. Can anyone lend a hand?


Solution

  • It depends on how the app is written, but frequently you can just write the answers to the prompts in a single write to stdin. Sometimes programs change their behavior depending on stdin type and you have to setup a tty (on linux) instead. In your case it sounds like the write works, so use communicate to write and close 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")