Executing the same batch file (.bat) using python - python

I developed the following loop for running the model with different rainfall ensemble using a loop. The script is working properly except for the execution process of my .bat file.
import os
import glob
import subprocess
ws = (r'C:\Users\Wahid Hussainzada\Desktop\Takahashi_2018_9_test')
os.chdir(ws)
myFile = glob.glob('*.txt')
myModel = glob.glob('2cdrmv3.bat')
for i in myFile:
if i.startswith('rain'):
print(i)
myBat = open(ws+'\wahid.bat','w+')
myBat.write('cdrmv3.exe param1.txt param2.txt param3.txt param4.txt bsndir.txt slope.txt length.txt order.txt takahashi_landuse.txt takahashi_acc.txt 0 # 1 takahashi_thiessen.txt 13 '+str(i) +' 0 1 out_'+str(i) +' 0 outgrid\outa2 outgrid\outb')
myBat.close()
subprocess.call('C:\Users\Wahid Hussainzada\Desktop\Takahashi_2018_9_test\wahid.bat')
else:
print("Other txt files than rain files")

try using string literals
subprocess.call(r'C:\Users\Wahid Hussainzada\Desktop\Takahashi_2018_9_test\wahid.bat')
you might have to do something like
cmd = r'C:\Windows\System32\cmd.exe'
script = r'C:\Users\Wahid Hussainzada\Desktop\Takahashi_2018_9_test\wahid.bat'
subprocess.call([cmd,script])

Based on #Joran Beasley answer the code can work with a minor revision as below:
cmd = r'C:\Windows\System32\cmd.exe'
script = r'Working directory\*.bat'
subprocess.call([script,cmd])

Related

How to write into a python driven config file from another python file

I have 2 python files. One is my main file mainFile.py and another file is basically a configuration file config.py
Structure of the config.py
class Configurations(object):
CONFIGURE_VM = True
CPU_CORES = 2
RAM = 96
THREADS = 2
This is how I am reading values of the config.py in my mainFile.py:-
from config import Configurations
def writeValues():
vm_configure = Configurations.CONFIGURE_VM
vcpu = Configurations.CPU_CORES
memory = Configurations.RAM
In my mainFile.py, I need to write the code to change the values of all the above parameters so that they can become something like:-
class Configurations(object):
CONFIGURE_VM = False
CPU_CORES = 1
RAM = 32
The use case is to read new values from the config.py everytime the mainFile.py runs and write new values in it.
Any help?
I could solve my own problem by using python FileInput library.
def writeValues(filename, input, output):
cwd = os.getcwd()
filename = os.path.join(cwd[:cwd.find('home')], 'home', 'config', filename)
for line in fileinput.input([filename], inplace=True):
line = line.strip("\n").split("=")
if input in line[0]:
line[1] = " " + str(output)
line = '='.join(line)
print(line)

imported function is not working when using it from another modules

I have been trying understand what is wrong with my code with no success...
I have two.py file which I have written with some function logs.py supposed to write an input to a file
and monitor_mode.py use thous function
When running the log.py as main everything just work fine and the file is created and written on, however when trying to use the same function in monitor_mode.py nothings seems to be written to the files and I have no idea why
I did try to debug and the code is directed to to right function and everything is going as excepted except there is no creation or data written to the file
thanks for any help
logs.py
serviceList = 'serviceList.txt'
statusLog = 'statusLog.txt'
def print_to_file(file_name, input):
with open(file_name, 'a+') as write_obj:
write_obj.write(input + '\n')
write_obj.close()
def add_timestamp(input):
timestamp = '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' + datetime.datetime.now().strftime(
"%Y-%m-%d %H:%M:%S") + '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
input = timestamp + '\n' + input
return input
if __name__ == "__main__":
import services
for i in range(3):
proc = services.list_of_process()
proc = add_timestamp(proc)
print_to_file(serviceList, proc)
monitor_mode.py
import logs
import services
serviceList = 'serviceList.txt'
statusLog = 'statusLog.txt'
def updates_log():
proc = services.list_of_process()
proc = logs.add_timestamp(proc)
logs.print_to_file(serviceList, proc)
print('Updates Logs\n' + proc)
if __name__ == "__main__":
for i in range(3):
updates_log()
EDIT1.1
the above code is running on ubuntu16.8
when running the code on win10 machine its working just fine.
services.list_of_process() - return a string

How do I convert multiple pictures, in a folder with ITK color map?

Every time I run my program in the terminal it prints out:
thumb0496.jpg is not converted
{} is not converted
Whatever I do it never works... I am new to Python and have installed it via Anaconda along with OpenCV, Pip and ITK. I have only been doing this for 4 days and am stuck. Python is my first language also. Why are my code not working?
In case this code looks similar it is. I had to try out with combining some elements. Unfortunately I cannot find the post again. The code was worse before but I (somehow) fixed it. It is just this (new) piece I can't fix on my own!
import cv2
import sys
import itk
import os,glob
from os import listdir,makedirs
from os.path import isfile,join
path = '/Users/admin/Desktop/ff'
dstpath = '/Users/admin/Desktop/test'
PixelType = itk.UC
Dimension = 2
ImageType = itk.Image[PixelType, Dimension]
RGBPixelType = itk.RGBPixel[PixelType]
RGBImageType = itk.Image[RGBPixelType, Dimension]
ColormapType = itk.CustomColormapFunction[PixelType, RGBPixelType]
colormap = ColormapType.New()
ColormapFilterType = itk.ScalarToRGBColormapImageFilter[ImageType,RGBImageType]
colormapFilter1 = ColormapFilterType.New()
colormapFilter1.SetInput(reader.GetOutput())
colormapFilter1.SetColormap(colormap)
WriterType = itk.ImageFileWriter[RGBImageType]
writer = WriterType.New()
writer.SetFileName(dstpath)
writer.SetInput(colormapFilter1.GetOutput())
try:
makedirs(dstpath)
except:
print ("Directory already exist, images will be written in same folder")
files = [f for f in listdir(path) if isfile(join(path,f))]
for image in files:
try:
reader = ReaderType(os.path.join(path,image))
map = ColormapFilterType(reader, PixelType, RGBImageType, ImageType)
dstPath = join(dstpath,image)
cv2.imwrite(dstPath,map)
except:
print ("{} is not converted".format(image))
for fil in glob.glob("*.jpg"):
try:
img = ReaderType(os.path.join(path,fil))
map_imag = ColormapType(img, PixelType, RGBImageType,ImageType)
cv2.imwrite(os.path.join(dstpath,fil),map_image)
except:
print('{} is not converted')
Why don't you start from a working example, and gradually change it to suit your needs? Examples can be found in the quick-start guide and this blog post.

How to route the Python script output to a file

I have a following script in python.
for i in range(10000):
print i
Above piece of python code prints the value of i from 0 to 9999 on the console.
Now I would like to route the output of the script directly to an external file.
On linux, I can get it done using the following command
$ python python_script.py > python_out.txt
What is the equivalent command on windows 7, IDLE Python Shell and under PyLab ?
Also, Above script prints numbers from 0 to 9999. I would like to take a snapshot of the output,
i.e. I want to route the first 85 records / numbers to out1.txt OR
I want to route the numbers that are divisible by 5 to out2.txt
without changing the actual script.
Also provide me the Python documentation to find out more.
file1, file2 = "out1.txt", "out2.txt"
with open(file1,'w') as f1,open(file2,"w") as f2:
for i in range(10000):
if i < 85:
f1.write("{0}\n".format(i)) # write to out1.txt
if i%5==0:
f2.write("{0}\n".format(i)) #write to out2.txt
print i #write to stdout or python_out.txt in your case
and run this program as:
$python python_script.py > python_out.txt
It is a bit ugly code, but you won't have to change your script.
class A:
def __init__(self, filename, predicate=(lambda ln, v:True)):
self.filename = filename
self.lines = 0
def write(self, text):
if predicate(self.lines, text):
with open(self.filename, 'a') as f:
f.write(text)
self.lines += text.count('\n')
Usage:
import sys
def predicate(linenumber, text):
if text.isdigit():
if int(text) % 5:
return False
return True
sys.stdout = A('out1.txt', predicate)
for i in range(10000):
print i
You have to open a file and write in it, something like this.
f = open('write_to_this_file.txt', 'w')
for i in xrange(10000):
f.write(i + "\n")
Here is more info http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files

python script for measuring battery time

I was looking for a script to log battery time (i.e. total time laptop runs on battery). I thought I'd give writing one a shot in python. I'm an beginner at python and came up with this using a lot of examples from this site :D
#!/usr/bin/env python
import subprocess, os
from datetime import datetime
time = (datetime.now()).strftime('%H:%M:%S')
date = (datetime.today()).strftime('%d/%m/%y')
def start(x):
if x[2] == 'Discharging' and int(x[3][:-1]) in range(98, 101):
batt_log = open('/home/saad/Code/batt_log', 'w')
batt_log.write(time + '%s' %(os.linesep))
batt_log.close()
def end(x):
if x[2] == 'Discharging' and int(x[3][:-1]) in range(1, 11):
batt_log = open('/home/saad/Code/batt_log', 'a')
batt_log.write(time)
batt_log.close()
def main():
output = subprocess.check_output('acpi -b', shell=True)
l = (output.replace(',', '')).split(' ')
if not (l[2] in ['Charging', 'Full'] or int(l[3][:-1]) in range(11, 98)):
start(l)
end(l)
ts = []
batt_log = open('/home/saad/Code/batt_log', 'r')
all_lines = batt_log.readlines()
for line in all_lines:
ts.append(line.replace(os.linesep, ''))
if len(ts) > 1:
FMT = '%H:%M:%S'
tdelta = datetime.strptime(ts[1], FMT) - datetime.strptime(ts[0], FMT)
batt_store = open('/home/saad/Code/batt_store', 'a')
batt_store.write(date + '\nTotal Time: ' + str(tdelta) + '\n')
batt_store.close()
batt_store = open('/home/saad/Code/batt_store', 'r')
all_lines = batt_store.readlines()
print "Last Battery Time:", all_lines[-1][-8:]
if __name__ == '__main__':
main()
The script actually works but I'd like it to be better. It uses system acpi command to get battery stats, writes them to one file (batt_log) to store start and end times, then reads from that file, calculates the time difference and writes it to another file (batt_store). I run it every 5 minutes as a process.
What I'd like to do is to maybe use less file I/O operations and find a way to store values persistently in the program. Any ideas welcome.
Getting data through command is far easier. In essence what acpi command would be doing is opening a file descriptor on specific file node in /dev/ . You could look at dbus interfaces for getting the information.
Regarding opening and closing of files, you could again use services like dbus or gconf but it is just easier writing a file.

Categories