subprocess run, check_output, popen returns empty string when i run the script from a batch file and from task scheduler

  • Last Update :
  • Techknowledgy :

First of all, if there is a need to run anaconda-prompt by calling activate.bat file, you can simply do as follows:

import subprocess

def call_anaconda_venv():
   subprocess.call('python -m venv virtual.env')
subprocess.call('cmd.exe /k /path/venv/Scripts/activate.bat')

if __name__ == "__main__":
   call_anaconda_venv()

Now First, script.bat includes a command that will run the required python script as given below;

python\ file_path\ test.py
pause

from subprocess
import check_output

class BatchCommands:

   @staticmethod
def run_commands_using_subprocess(commands):
   print("Running commands from File: {}".format(commands))
value = check_output(commands, shell = True).decode()

return value

@staticmethod
def run():
   commands_from_file = "\file-path\sys_info.bat"

print('##############################################################')
print("Shell Commands using >>> subprocess-module  <<<")
print('##############################################################')

values = BatchCommands.run_commands_using_subprocess(commands_from_file)
print(values)

if __name__ == '__main__':
   BatchCommands.run()

Place multiple commands in sys_info.bat file, then you can also run multiple commands at a time like:

ipconfig / all
ipconfig / release
ipconfig / reset
ipconfig / renew
ipconfig

Run command-prompt or terminal as an administrator.

 run\ file_path\ script.py

Run command-prompt or terminal as an administrator.

 run\ file_path\ script.py

Suggestion : 2

I have tried subprocess.check_output, anycodings_python subprocess.run, subprocess.Popen, all of anycodings_python them returns me an empty string only when anycodings_python running it using a batch file.,When ran in batch file and from task anycodings_python scheduler:,Get the currently executing script element inside a type="module" script,I have a batch file which is running a anycodings_python python script and in the python script, I anycodings_python have a subprocess function which is being anycodings_python ran.

If I run it manually or using an IDE, I get anycodings_python the response correctly. Below is the code anycodings_python for subprocess.run:

    response = subprocess.run(fileCommand, shell = True, cwd = pSetTableauExeDirectory, capture_output = True)
    self.writeInLog(' Command Response: \t' + str(response))

Batch file which runs the python program. anycodings_python Parameters are parsed to the python anycodings_python application

SET config = SampleSuperStore.txt
CALL C: \XXX\ AppData\ Local\ Continuum\ anaconda3\ Scripts\ activate.bat
C: \XXX\ AppData\ Local\ Continuum\ anaconda3\ python.exe Z: \XXX\ pMainManual.py "%config%"

--Complete python code---

try:
from pWrapper
import wrapper
import sys
except Exception as e:
   print(str(e))

class main:

   def __init__(self):
   self.tableauPath = 'C:\\Program Files\\Tableau\\Tableau 2018.3\\bin\\'
self.tableauCommand = 'tableau refreshextract --config-file'

def runJob(self, argv):
   self.manual_sProcess(argv[1])

def manual_sProcess(self, tableauConfigFile):
   new_wrapper = wrapper()
new_wrapper.tableauSetup(self.tableauPath, self.tableauCommand)
if new_wrapper.tableauConfigExists(tableauConfigFile):
   new_wrapper.tableauCommand(tableauConfigFile)

if __name__ == "__main__":
   new_main = main()
new_main.runJob(sys.argv)

Automate Class:

def runCommand(self, pConfig, pCommand, pRefreshConfigCommand, pFilePath, pSetTableauExeDirectory):
   try:
   fileCommand = pRefreshConfigCommand + ' "' + pFilePath + '"'
response = subprocess.run(fileCommand, shell = True, cwd = pSetTableauExeDirectory, capture_output = True)
self.writeInLog(' Command Response: \t' + str(response))
except Exception as e:
   self.writeInLog('Exception in function runCommand: ' + str(e))

First of all, if there is a need to run anycodings_python-3.x anaconda-prompt by calling activate.bat anycodings_python-3.x file, you can simply do as follows:

import subprocess

def call_anaconda_venv():
   subprocess.call('python -m venv virtual.env')
subprocess.call('cmd.exe /k /path/venv/Scripts/activate.bat')

if __name__ == "__main__":
   call_anaconda_venv()

Now First, script.bat includes a command anycodings_python-3.x that will run the required python script anycodings_python-3.x as given below;

python\ file_path\ test.py
pause

from subprocess
import check_output

class BatchCommands:

   @staticmethod
def run_commands_using_subprocess(commands):
   print("Running commands from File: {}".format(commands))
value = check_output(commands, shell = True).decode()

return value

@staticmethod
def run():
   commands_from_file = "\file-path\sys_info.bat"

print('##############################################################')
print("Shell Commands using >>> subprocess-module  <<<")
print('##############################################################')

values = BatchCommands.run_commands_using_subprocess(commands_from_file)
print(values)

if __name__ == '__main__':
   BatchCommands.run()

Place multiple commands in sys_info.bat anycodings_python-3.x file, then you can also run multiple anycodings_python-3.x commands at a time like:

ipconfig / all
ipconfig / release
ipconfig / reset
ipconfig / renew
ipconfig

Run command-prompt or terminal as an anycodings_python-3.x administrator.

 run\ file_path\ script.py

Run command-prompt or terminal as an anycodings_python-3.x administrator.

 run\ file_path\ script.py

Suggestion : 3

Subclass of SubprocessError, raised when a process run by check_call(), check_output(), or run() (with check=True) returns a non-zero exit status.,check_call() and check_output() will raise CalledProcessError if the called process returns a non-zero return code.,Subclass of SubprocessError, raised when a timeout expires while waiting for a child process.,Output of the child process if it was captured by run() or check_output(). Otherwise, None.

os.system
os.spawn *
>>> subprocess.run(["ls", "-l"]) # doesn 't capture output
CompletedProcess(args = ['ls', '-l'], returncode = 0)

   >>>
   subprocess.run("exit 1", shell = True, check = True)
Traceback(most recent call last):
   ...
   subprocess.CalledProcessError: Command 'exit 1'
returned non - zero exit status 1

   >>>
   subprocess.run(["ls", "-l", "/dev/null"], capture_output = True)
CompletedProcess(args = ['ls', '-l', '/dev/null'], returncode = 0,
   stdout = b 'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr = b '')
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
>>>
import shlex, subprocess
   >>>
   command_line = input() /
   bin / vikings - input eggs.txt - output "spam spam.txt" - cmd "echo '$MONEY'" >>>
   args = shlex.split(command_line) >>>
   print(args)['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"] >>>
   p = subprocess.Popen(args) # Success!
Popen(['/bin/sh', '-c', args[0], args[1], ...])
with Popen(["ifconfig"], stdout = PIPE) as proc:
   log.write(proc.stdout.read())

Suggestion : 4

This is basically just like the Popen class and takes all of the same arguments, but it simply wait until the command completes and gives us the return code.,The underlying process creation and management in this module is handled by the Popen class. It offers a lot of flexibility so that developers are able to handle the less common cases not covered by the convenience functions.,os.system('command with args') passes the command and arguments to our system's shell. By using this can actually run multiple commands at once and set up pipes and input/output redirections. :,If args is a string, the string specifies the command to execute through the shell. This means that the string must be formatted exactly as it would be when typed at the shell prompt. This includes, for example, quoting or backslash escaping filenames with spaces in them:

Popen
Popen(['/bin/sh', '-c', args[0], args[1], ...])