Execute bash script from Python on Windows

2024/9/19 10:06:05

I am trying to write a python script that will execute a bash script I have on my Windows machine. Up until now I have been using the Cygwin terminal so executing the bash script RunModels.scr has been as easy as ./RunModels.scr. Now I want to be able to utilize subprocess of Python, but because Windows doesn't have the built in functionality to handle bash I'm not sure what to do.

I am trying to emulate ./RunModels.scr < validationInput > validationOutput

I originally wrote this:

os.chdir(atm)
vin = open("validationInput", 'r')
vout = open("validationOutput", 'w')
subprocess.call(['./RunModels.scr'], stdin=vin, stdout=vout, shell=True)
vin.close()
vout.close()
os.chdir(home)

But after spending a while trying to figure out why my access was denied, I realized my issue wasn't the file permissions but the fact that I was trying to execute a bash file on Windows in general. Can someone please explain how to execute a bash script with directed input/output on windows using a python script?

Edit (Follow up Question):

Thanks for the responses, I needed the full path to my bash.exe as the first param. Now however, command line calls from within RunModels.scr come back in the python output as command not found. For example, ls, cp, make. Any suggestions for this?

Follow up #2: I updated my call to this:

subprocess.call(['C:\\cygwin64\\bin\\bash.exe', '-l', 'RunModels.scr'], stdin=vin, stdout=vout, cwd='C:\\path\\dir_where_RunModels\\')

The error I now get is /usr/bin/bash: RunModels.scr: No such file or directory. Using cwd does not seem to have any effect on this error, either way the subprocess is looking in /usr/bin/bash for RunModels.scr.

SELF-ANSWERED I needed to specify the path to RunModels.scr in the call as well as using cwd.

subprocess.call(['C:\\cygwin64\\bin\\bash.exe', '-l', 'C:\\path\\dir_where_RunModels\\RunModels.scr'], stdin=vin, stdout=vout, cwd='C:\\path\\dir_where_RunModels\\')

But another problem...

Regardless of specifying cwd, the commands executed by RunModels.scr are throwing errors as if RunModels.scr is in the wrong directory. The script executes, but cp and cd throw the error no such file or directory. If I navigate to where RunModels.scr is through the command line and execute it the old fashioned way I don't get these errors.

Answer

Python 3.4 and below

Just put bash.exe in first place in your list of subprocess.call arguments. You can remove shell=True, that's not necessary in this case.

subprocess.call(['C:\\cygwin64\\bin\\bash.exe', '-l', 'RunModels.scr'], stdin=vin, stdout=vout,cwd='C:\\path\\dir_where_RunModels\\')

Depending on how bash is installed (is it in the PATH or not), you might have to use the full path to the bash executable.

Python 3.5 and above

subprocess.call() has been effectively replaced by subprocess.run().

subprocess.run(['C:\\cygwin64\\bin\\bash.exe', '-l', 'RunModels.scr'], stdin=vin, stdout=vout,cwd='C:\\path\\dir_where_RunModels\\')

Edit:

With regard to the second question, you might need to add the -l option to the shell invocation to make sure it reads all the restart command files like /etc/profile. I presume these files contain settings for the $PATH in bash.

Edit 2:

Add something like pwd to the beginning of RunModels.scr so you can verify that you are really in the right directory. Check that there is no cd command in the rc-files!

Edit 3:

The error /usr/bin/bash: RunModels.scr: No such file or directory can also be generated if bash cannot find one of the commands that are called in the script. Try adding the -v option to bash to see if that gives more info.

https://en.xdnf.cn/q/72655.html

Related Q&A

Python regex convert youtube url to youtube video

Im making a regex so I can find youtube links (can be multiple) in a piece of HTML text posted by an user.Currently Im using the following regex to change http://www.youtube.com/watch?v=-JyZLS2IhkQ in…

Python / Kivy: conditional design in .kv file

Would an approach similar to the example below be possible in Kivy? The code posted obviously doesnt work, and again its only an example: I will need different layouts to be drawn depending on a certa…

z-axis scaling and limits in a 3-D scatter plot

I performed a Monte Carlo inversion of three parameters, and now Im trying to plot them in a 3-D figure using Matplotlib. One of those parameters (Mo) has a variability of values between 10^15 and 10^2…

How to fix value produced by Random?

I got an issue which is, in my code,anyone can help will be great. this is the example code.from random import * from numpy import * r=array([uniform(-R,R),uniform(-R,R),uniform(-R,R)])def Ft(r):f…

Can I safely assign to `coef_` and other estimated parameters in scikit-learn?

scikit-learn suggests the use of pickle for model persistence. However, they note the limitations of pickle when it comes to different version of scikit-learn or python. (See also this stackoverflow qu…

How to update the filename of a Djangos FileField instance?

Here a simple django model:class SomeModel(models.Model):title = models.CharField(max_length=100)video = models.FileField(upload_to=video)I would like to save any instance so that the videos file name …

CSS Templating system for Django / Python?

Im wondering if there is anything like Djangos HTML templating system, for for CSS.. my searches on this arent turning up anything of use. I am aware of things like SASS and CleverCSS but, as far as I …

How to use chomedriver with a proxy for selenium webdriver?

Our network environment using a proxy server to connect to the outside internet, configured in IE => Internet Options => Connections => LAN Settings, like "10.212.20.11:8080".Now, Im…

django application static files not working in production

static files are not working in production even for the admin page.I have not added any static files.I am having issues with my admin page style.I have followed the below tutorial to create the django …

Celery task in Flask for uploading and resizing images and storing it to Amazon S3

Im trying to create a celery task for uploading and resizing an image before storing it to Amazon S3. But it doesnt work as expected. Without the task everything is working fine. This is the code so fa…