user3349459
user3349459

Reputation: 29

How to call relative path of batch file from python

How do I call the relative path of batch file from python?

My python script 'Script.py' is in the directory "d:\2014\python\script.py" from this file i would like to call a batch file "d:\2014\input\batch1.bat" but i want to use relative path with popen() function.

In Script.py

import os, sys
from subprocess import Popen
p = Popen("D:\\2014\\input\\batch1.bat", cwd=r"D:\\2014\\input")
stdout, stderr = p.communicate()

the above code will work but the below code will not work

p = Popen("..\\input\\batch1.bat", cwd=r"..\\input")
stdout, stderr = p.communicate()

gives file not found error

Upvotes: 1

Views: 4856

Answers (2)

SiHa
SiHa

Reputation: 8411

From the python docs:

"If cwd is not None, the child’s current directory will be changed to cwd before it is executed. Note that this directory is not considered when searching the executable, so you can’t specify the program’s path relative to cwd."

A very similar question was posed here, try:

[...]
fn = os.path.join(os.path.dirname(__file__), "..\\input\\batch1.bat")
p = Popen(fn, cwd=r"D:\\2014\\input")
[...]

Upvotes: 1

HSquirrel
HSquirrel

Reputation: 849

Python will take the path from which you execute as the current directory. You can retrieve the current directory with os.getcwd().

Let's say I have a python script on my desktop to test this called pycwd.py:

import os
print os.getcwd()

Called from different places, it'll give different results:

C:\Users\me>python Desktop\pycwd.py
C:\Users\me
C:\Users\me\Desktop>python pycwd.py
C:\Users\me\Desktop

You'd want to use the solution SiHa suggested above:

path_to_directory_of_this_python_file = os.path.dirname(__file__)
path_to_your_batch_file = os.path.join(path_directory_of_this_python_file, '..', 'input', 'batch1.bat')
p = Popen(path_to_your_batch_file)

The cwd argument in Popen is the path from where you want to execute your batchfile (f.e. if the batchfile expects to be only called from a certain directory). EDIT: so for your jarfile: set cwd in popen to the directory where your jar file resides. Can you give this as a relative path to either the python file or the batch file or is it an absolute path only?

Upvotes: 2

Related Questions