0

How can I run a batch file with Python (in the same directory as the Python scripts)?

Note that the directory cannot be constant as it can be changed from one user to another.

Mike Müller
  • 71,943
  • 15
  • 139
  • 140
Bacem Tayeb
  • 25
  • 1
  • 7
  • 1
    take a look at the [subprocess](https://docs.python.org/3/library/subprocess.html) library for calling external commnads (like bat files) – Aaron Jan 12 '17 at 22:05
  • Possible duplicate of [Calling an external command in Python](http://stackoverflow.com/questions/89228/calling-an-external-command-in-python) – turbulencetoo Jan 12 '17 at 22:05
  • @turbulencetoo, the only respect in which I'm not sure that's a dupe is inasmuch as finding the command to be run *relative to the Python source file's location* is an element of this one. – Charles Duffy Jan 12 '17 at 22:06

2 Answers2

2

You need to find out where your script is and assemble an absolute path:

import os
import subprocess

dirname = os.path.dirname(os.path.abspath(__file__))
cmd = os.path.join(dirname, 'mybatch_file')

subprocess.call(cmd)

In Steps

You can find out the name of script with:

__file__

Now make it an absolute path:

os.path.abspath

and get the directory it is in:

os.path.dirname

Finally, join this path with your batch file name:

os.path.join

before you feed it to:

subprocess.call
Mike Müller
  • 71,943
  • 15
  • 139
  • 140
0

you can achieve it use subprocess module

from subprocess import call
comando = 'path_to_the_script'
call(comando, shell=True)
Leonardo Hermoso
  • 808
  • 11
  • 24