'How to run a fully functional batch file from a python script?

I look after a Lab with a number of Rigs in it and I am developing an automated process for running experiments. The trigger for loading the experiments is to use a particular username. I have a flowchart that identifies behaviours when logging on so that when a rig is booked to the particular username and nobody else is logged on, then it takes over and runs experiments during the night etc.

I need to be able to use python to run a batch file to log users off (unless there is a python command I can use). I have written a batch file that does this (LogOffIP.bat). If I run the batch file from a command prompt, it works fine and the users (chosen by the session id on the remote PC) get logged off and all is well.

I have a python script that calls the bat file with the same arguments and the command prompt pops up and runs but I get a different response like " 'logoff' is not recognized as an internal or external command", and the same for quser.

Please check out my code below and help me find a python solution. Thanks...

LogOffIP.bat:

@echo off
echo Logging off Rig %1
echo at IP address %2
echo using session ID %3
echo.
echo.
logoff %3 /server:%2
echo Done...
echo
quser /server:%2
pause
rem exit

From python...

I have tried:

import os os.system(r"path\LogOffIP.bat G 100.100.100.100 12")

this gives 'logoff' is not recognized.

I have tried:

import subprocess
answer = subprocess.call([path\LogOffIP.bat, G, 100.100.100.100, 1'])

this gives WindowsError: [Error 2] The system cannot find the file specified in python.

I have tried: answer = subprocess.Popen([r'path','LogOffIP.bat','G 100.100.100.100 1'])

this gives WindowsError: [Error 5] Access is denied in python

I have used bogus IP addresses in the examples to protect the real ones.

I expect a short delay and the user is logged off as seen when running the batch file from a command prompt. os.system doesn't seem to support all the dos commands.



Solution 1:[1]

Try the following...

import subprocess
answer = subprocess.call([r'LogOffIP.bat', G, 100.100.100.100, 1'])

This is assuming that LogOffIP.bat is in the same directory as the .py file

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 BJonas88