A
A
amaterasu02020-01-30 17:10:29
Python
amaterasu0, 2020-01-30 17:10:29

How to run a python program using a bat file and enter data into it?

I have a python program with input and I need to run it through a bat file, and also enter data into this program through this file. Is that possible?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Pankov, 2020-01-30
@amaterasu0

Of course available. I don’t have Windows at hand right now, but it will look something like this.
Program, let's call it my_python_script.py :

x = input()
print('Text from input:', x)

batch file:
echo the string for python | python my_python_script.py

If there are several inputs, then you need to transfer several lines.
To do this with echo, you need to write a line with a paragraph inside. I have no idea how a paragraph is escaped in bat files, so I can offer this option.
my_python_script.py:
x = input()
y = input()
z = input()
rest = []
while z != 'END':
    rest.append(z)
    z = input()

print('x=', x, 'y=', y)
print('rest=', rest)

my_script.bat:
echo The X string
echo The Y string
echo Other string 1
echo line 2
echo line 3
echo line 4
echo END

We call it like this:
my_script.bat | python.exe my_python_script.py
All the output from the batch file will go to the input of the Python script.
You can make another batch file that will make such a call. You can describe a subroutine inside the batch file that will print lines and call it in the same batch file with a pipe with a transfer to the python.
A pipe is a virtual file in the operating system that can either be read or written. or both. Depends on how the pipe is made. For each program, the system creates three pipes at startup: stdin, stdout, stderr.
Using `|` on the command line between commands, you can make a pipe, when the output of the left command in stdout is directed to the input of the right command in stdin. With such a locomotive, you can connect as many teams as you like.
With `>` you can redirect stdout to a local file with a given name:
echo text to write into the file > the_file.txt
With `<` you can pipe the contents of a file to stdin.
There are a lot of tricks with these redirects, but it's better to read the profile article or documentation.
Python reads with input() from stdin and writes with print to stdout by default. echo in a bat file also writes to stdout.
In Linux (and in Windows, if you install shell support), there are a bunch of other useful commands and utilities for working on the command line (cat, tee, ...)

X
xDimus, 2020-01-30
@xDimus

You can do this
inp.py:

a = input()
b = input()
c = input()
print(a, b, c)

inp.txt
11
22
33

run from command line or by putting this in inp.bat:
inp.py < inp.txt
result:
11 22 33

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question