I have a Python script which loops through a folder, creating a shell command for each file.
Each command is written to a shell script and this script is then run using subprocess.Popen. (I need to do this because I also need to set up the environment before for the commands to work).
Here is some pseudocode:
'''loop through a folder, create a command for each file and write this to a shell script'''
# command to run
#list of files
#loop through the files to create a folder
for file in my_folder:
# open the shell script
shellscript = open(scriptname,'w')
# set the environment using '.' as using bash below to run shell script
#loop through commands and write to shellscript
for command in command_list:
# use subprocess to run the shell script. Use bash to interpret the environment
proc = subprocess.Popen([cmd], stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
You should close the
shellscript file object after writing the commands to it and before running it via
Popen. Otherwise, the file might not be written completely before you execute it.
The most elegant solution is to use a context manager, which closes the file automatically:
with open(scriptname, "w") as f: f.write(...)