pythonsubprocessglob

Python, using glob with cwd argument to subprocess.call


I want to call a subprocess in python using subprocess.call(), with the 'cwd' argument so that this particular subprocess is executed in a different directory. I don't want to use os.chdir() because for future processes later in the program I want to remain in the original directory from where the program was run.

BUT, I also want to run this particular subprocess on a set of files matching a glob pattern. So for example, I might want to do

subprocess.call(['ls'] + glob('*.txt'), cwd="/my/other/dir/")

But of course the glob command doesn't know to look in /my/other/dir, so it fails. How can I do this without using shell=True?


Solution

  • For anyone looking at this since 2021, a feature for this was added to glob.glob in Python 3.10. See the release notes here.

    So, this can be done as follows:

    my_other_dir = "/my/other/dir/"
    subprocess.call(['ls'] + glob('*.txt', root_dir=my_other_dir), cwd=my_other_dir)