tmsblgh
tmsblgh

Reputation: 527

Python subprocess.Popen in other directory

I have this command:

grep = subprocess.Popen('head -20'.split(), stdin=subprocess.PIPE, stdout=subprocess.PIPE)
ls = subprocess.Popen('ls'.split(), stdout=grep.stdin)
output_lines = grep.communicate()[0]

How can I run this command in other directory? For example in /home/?

Upvotes: 1

Views: 1393

Answers (3)

jfs
jfs

Reputation: 414605

To avoid changing the global process working directory with os.chdir() (that you don't want if your program uses multiple threads), you could pass cwd='/home' parameter to Popen().

Upvotes: 3

DeepSpace
DeepSpace

Reputation: 81654

With chdir:

import os

os.getcwd()
>> 'a/sample/path'

os.chdir('/home/')

os.getcwd()
>> '/home/'

Upvotes: 0

Barry Scott
Barry Scott

Reputation: 819

The subprocess will inherits the python processes current working directory. Just change the directory before calling Popen. For example:

import os

old_dir = os.getcwd()
os.chdir( '/home' )
grep = subprocess.Popen( ... )
os.chdir( old_dir )

Upvotes: 1

Related Questions