2

I am trying to run a bash while loop inside a Python3.6 script. What I have tried so far is:

subprocess.run(args=['while [ <condition> ]; do <command> done;'])

I get the following error:

FileNotFoundError: [Errno 2] No such file or directory

Is there a way to run such a while loop inside Python?

6
  • 1
    Welcome to SO: Please take the tour and read with attention minimal reproducible example. Show us your code that we can help you. Commented Aug 23, 2017 at 18:21
  • 1
    This is missing a shell=True keyword argument. As is, you are trying to execute a binary with the name of the passed in string`. And note that I have never seen any need for this. Commented Aug 23, 2017 at 18:29
  • 2
    while is no program, it is a bash builtin command. Try bash -c "while ..." Commented Aug 23, 2017 at 18:31
  • Thanx @dhke that worked. Commented Aug 23, 2017 at 18:47
  • The argument you should pass is ['/bin/bash', '-c', ' .. your code ..']. That way you can control stdout and stderr if you need. Commented Aug 23, 2017 at 19:40

2 Answers 2

1

The part that's tripping you up is providing the args as a list. From the documentation:

If the cmd argument to popen2 functions is a string, the command is executed through /bin/sh. If it is a list, the command is directly executed.

This seems to do what you want:

subprocess.run('i=0; while [ $i -lt 3 ]; do i=`expr $i + 1`; echo $i; done', shell=True)

Notice it's specified as a string instead of a list.

Sign up to request clarification or add additional context in comments.

Comments

1

Running bash for loop in Python 3.x is very much like running while loop.

#! /bin/bash

for i in */;
do
    zip -r "${i%/}.zip" "$i";
done

This will iterate over a path and zip all directories. To run above bash script in Python:

import subprocess

subprocess.run('for i in */;  do zip -r "${i%/}.zip" "$i"; done', shell=True)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.