Reputation: 150
I am wondering if it is possible to execute bash code from within a python file. I don't mean run a completely different bash file. I am looking for a method to easily execute bash code that is one line or longer in length. Specifically, I want to execute this code I got help with from a question I asked earlier today.
shopt -s nullglob
dirs=(*/)
cd -- "${dirs[RANDOM%${#dirs[@]}]}"
Upvotes: 4
Views: 481
Reputation: 414865
To run a string 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 specify the command explicitly:
x(["bash", "-c", '''shopt -s nullglob
dirs=(*/)
pwd
cd -- "${dirs[RANDOM%${#dirs[@]}]}"
pwd'''])
Note: it only checks whether you can cd
into a random subdirectory. The change is not visible outside the bash script.
You could do it 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 could also use glob
:
from glob import glob
randomdir = random.choice(glob("*/"))
The difference compared to os.listdir()
is that glob()
filters directories that start 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)])
Upvotes: 4
Reputation: 4889
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 (nicer) looping and conditional execution facilities.
Upvotes: 0
Reputation: 9413
The best way is to use commands module
eg:
>>> import commands
>>> (status,output)=commands.getstatusoutput("ls")
>>> print(output)#print the output
>>> print(status)#print the status of executed command
Upvotes: 0
Reputation: 388383
You can use os.system
or functions from the subprocess module with the shell
parameter set to true.
Note that many of the things you do in bash can be made just as easily within Python, while maintaining platform independence. For example I tried to run a Python script on Windows recently which was using many unix commands to do simple things like grepping some text and as such failed.
Upvotes: 1