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)])