Home > Net >  Auto-send inputs to another python script
Auto-send inputs to another python script

Time:12-14

I have a python script that accepts 2 user inputs before it goes away and does something. I'm in a position where I now need to run the script multiple times, with different values for either of the 2 inputs. I'd rather not have to keep re-running the script and manually enter the values each time as I have over 100 different combinations. I believe this can be done fairly fluidly in python.

Here is an example: input.py

import pandas as pd

# Variables for user input
print("Please enter your name: ")
UserInput = input()
name = str(UserInput)
print("Now enter your Job title: ")
UserInput2 = input()
job = str(UserInput2)

# Create filename with name and current date
currenttime = pd.to_datetime('today').strftime('%d%m%Y')
filename = name   '_'   currenttime   ".csv"

print('\nHi '   name   '. ')
print('Hope your job as a '   job   ' is going well.')
print("I've saved your inputs to "   filename)
print('Speak to you soon. Bye.')

# Create DataFrame, append inputs and save to csv
series = pd.Series({'Name ': name, 'Job Title ': job})
df = pd.DataFrame([series])
df.to_csv(filename, index=False)

Below is my attempt of auto-sending inputs to input.py using the subprocess module (might not be the correct approach). The file calls input.py successfully, but I cannot figure what other arguments I need to add to send the specified values. Code used: auto.py

import subprocess
subprocess.run(['python', 'input.py'])
# These don't work
#subprocess.run(['python', 'input.py', 'Tim', 'Doctor'])
#subprocess.run(['python', 'input.py'], input=('Tim', 'Doctor'))
#subprocess.run(['python', 'input.py'], stdin=('Tim', 'Doctor'))

Ideally I want to have a list of the different inputs I want to send to the script so that it loops and adds the second batch of inputs, loops again then third batch and so on. I'm unsure if I'm using correct subprocess method. Any help would be greatly appreciated.

CodePudding user response:

Use something like this in your input.py

import pandas as pd
import sys


# Variables for user input
UserInput = sys.argv[0]
name = str(UserInput)
UserInput2 = sys.argv[1]
job = str(UserInput2)

# Create filename with name and current date
currenttime = pd.to_datetime('today').strftime('%d%m%Y')
filename = name   '_'   currenttime   ".csv"

print('\nHi '   name   '. ')
print('Hope your job as a '   job   ' is going well.')
print("I've saved your inputs to "   filename)
print('Speak to you soon. Bye.')

# Create DataFrame, append inputs and save to csv
series = pd.Series({'Name ': name, 'Job Title ': job})
df = pd.DataFrame([series])
df.to_csv(filename, index=False)

auto.py will be

import subprocess
subprocess.run(['python', 'input.py','Tim', 'Doctor'])

let me know if that helps and I can modify your need accordingly.

auto.py output:

enter image description here

  • Related