How to execute bash from python file?

I am wondering if bash code can be executed from a python file. I do not want to run a completely different bash file. I am looking for a method to easily execute bash code that is one line or longer. In particular, I want to execute this code, with which I received help, from a question that I asked earlier today.

shopt -s nullglob dirs=(*/) cd -- "${dirs[RANDOM%${#dirs[@]}]}" 
+4
source share
5 answers

To run a line as a sh script (assuming POSIX):

 #!/usr/bin/env python from subprocess import check_call as x x("""pwd cd / pwd""", shell=True) 

You can explicitly specify the command:

 x(["bash", "-c", '''shopt -s nullglob dirs=(*/) pwd cd -- "${dirs[RANDOM%${#dirs[@]}]}" pwd''']) 

Note: it checks if you can cd into a random subdirectory. This change is not visible outside the bash script.

You can do this without bash:

 #!/usr/bin/env python import os import random print(os.getcwd()) os.chdir(random.choice([d for d in os.listdir(os.curdir) if os.path.isdir(d)])) print(os.getcwd()) 

You can also use glob :

 from glob import glob randomdir = random.choice(glob("*/")) 

The difference compared to os.listdir() is that glob() filters directories starting with a dot . . You can filter it manually:

 randomdir = random.choice([d for d in os.listdir(os.curdir) if (not d.startswith(".")) and os.path.isdir(d)]) 
+4
source

You can execute bash code, but any of its effects (especially cd ) will only affect the subprocess in which it works, so it makes no sense. Most likely, all of this does a great job with Python commands (see glob ).

+1
source

You can use os.system or subprocess functions with the shell parameter set to true.

Note that many of the things you do in bash can be done just as easily in Python, while maintaining platform independence. For example, I tried running a Python script on Windows recently, which used many unix commands to do simple things like grepping some text and as such failed.

+1
source

The best way is to use the command module

eg:

 >>> import commands >>> (status,output)=commands.getstatusoutput("ls") >>> print(output)#print the output >>> print(status)#print the status of executed command 
0
source

You can also do this.

 import os os.system("system call 1") os.system("system call 2") (etc) 

You can write shell scripts this way and use Python (more convenient) features and conditional execution.

0
source

All Articles