[Tutor] Executing a .sh script in a for loop

Mats Wichmann mats at wichmann.us
Wed Aug 19 10:12:03 EDT 2020


On 8/19/20 3:00 AM, Alan Gauld via Tutor wrote:
> On 19/08/2020 06:54, D.P.Noone at lumc.nl wrote:
> 
>> for root, dirs, files in os.walk("."):
>>   for filename in files:
>>     if filename.endswith("fileending.txt"):
>>       subprocess.Popen('./script.sh',)
>>       print("Done")
> 
>> This is the same as if I just type script.sh in the command line in linux, 
>> but do not target it to any file specifically. i.e.
> 
> Correct. You have just answered your own question.
> How do you suppose script.sh is supposed to know what your
> python code is doing? There is no magic communication channel.
> You need to tell it the file name when you call it just as
> you do at the command line.
> 
> Popen() can take arguments as well as the script name.
> 
> sub.Popen( ['./script.sh', filename] )
> 

In addition, if using the Popen constructor directly, you need to manage
this connection a little better - making sure the script has completed,
collecting any results, etc.

It's easier to use one of the convenience methods: I prefer
subprocess.run(), which handles the whole deal, and gives you back an
instance of the nice CompletedProcess class.  This is now highlighted at
the very top of the subprocess documentation:

https://docs.python.org/3/library/subprocess.html




More information about the Tutor mailing list