0

I'm having a problem passing some arguments through my python script to a test.bat file.

//test.bat
@echo off
:: Extracting and input arguments
set IP=%1
set PASS=%~2
set DIR=%~3

:: Setup logfile
set LOG_FILE="%cd%\testLog.log"
if exist %LOG_FILE% del %LOG_FILE%

echo -------------------------------------------------------- >> %LOG_FILE%
echo Date    :  %date% >> %LOG_FILE%
echo Time    :  %time% >> %LOG_FILE%
echo IP      :  %IP% >> %LOG_FILE%
echo PW      :  %PASS% >> %LOG_FILE%
echo PATH    :  %DIR% >> %LOG_FILE%
.....

test.py

p = subprocess.Popen('test.bat', stdin = subprocess.PIPE)
ipAdr = '127.0.0.1'
pasWD = 'root'
locPath = 'C:\repos\batTester'

p.stdin.write(bytes(ipAdr , 'ascii')) #IP
p.stdin.write(bytes(pasWD , 'ascii')) #password
p.stdin.write(bytes(locPath , 'ascii'))#directory

I see, that bath file is run correctly, because testLog.log file is created, but IP, PW, and DIR fields are empty, so the rest of the script can't be executed. How should I pass multiple arguments to a .bat file using a python script?

1
  • 1
    BTW, you can change that entire batch file to this, which is more efficient. 1. @(Echo --------------------------------------------------------, 2. Echo Date : %DATE%, 3. Echo Time : %TIME, 4. Echo IP : %~1, 5. Echo PW : %~2, 6. Echo PATH : %~3) 1> "testLog.log". There is no need to define environment variables for the input arguments, (as those are already saved to argument variables), or to open a file, write to it, and then close it, for every single echo command. Commented Oct 24, 2021 at 13:28

1 Answer 1

1

Try to run subprocess.run:

p = subprocess.run(['test.bat', ipAdr, pasWD, locPath])
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks ;) I have one more question. The file test.bat connects to a specified IP address, but if the host is unreachable the whole application freezes for quite a long time. Is there any easy way to avoid this? The only thing I can think of is running the 'subprocess' as a separate thread.
You have a timeout parameter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.