Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automate Input Into Python Prompts

Tags:

python

bash

I am trying to write a python script which will execute a bash command line program for me. This program asks for user input twice, and I want my script to automatically enter "1" each time.

I've heard of something like this:

os.system("program < prepared_input")

How do I write prepared_input? Thanks.

like image 652
Dana Gray Avatar asked Sep 15 '26 05:09

Dana Gray


1 Answers

Create file with two lines:

1
1

And use read in the bash script to get the input:

Demo:

$ cat abc
1
1
$ cat so.sh
#!/bin/bash
read data
echo "You entered $data"
read data
echo "Now you entered $data"
$ bash so.sh <abc
You entered 1
Now you entered 1

Python :

>>> import os
>>> os.system("bash so.sh < abc")
You entered 1
Now you entered 1
0
like image 81
Ashwini Chaudhary Avatar answered Sep 16 '26 18:09

Ashwini Chaudhary