简体   繁体   中英

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?

You could use the CWD in the glob pattern as well. Like glob.glob("/my/other/dir/*.txt") . It will expand with full match, like /my/other/dir/aa.txt . In case you do not want to pass the full path to the executable, cut it off.

CWD = "/my/other/dir/"
files = map(lambda x: x[len(CWD):], glob.glob(CWD + "*.txt"))
subprocess.call(['ls'] + files, cwd=CWD)

Or you could just change the directory back after the subprocess has finished.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM