4

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[@]}]}"
2
  • You may want to take a look at Fabric if you do this a lot. Commented Jan 5, 2013 at 18:00
  • Also, why not just os.chdir(random.choice(filter(os.path.isdir, os.listdir('.'))))? Commented Jan 5, 2013 at 18:04

5 Answers 5

4

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)])
Sign up to request clarification or add additional context in comments.

Comments

1

You can execute bash code, but any effects of it (notably, cd) will only affect the subprocess it runs in, so there is no point. Rather, all of this is perfectly doable with Python commands (look into glob).

Comments

1

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.

2 Comments

Warning: shell = True can be a huge security hole!
@ncmathsadist OP was asking how to execute something inside the shell though ;)
0

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

1 Comment

“Platforms: Unix” and “Deprecated since version 2.6”.
0

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.

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.