Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: run shell command in a specific directory [duplicate]

Tags:

python

shell

I use python script to compile a maven project.

If I use

from subprocess import call
call("mvn clean && mvn compile")

I can't define the directory of my maven project and maven tries to compile in directory of Python script.

Is there any standard way to define execution directory for the shell command?

like image 441
Alexander Teut Avatar asked Dec 24 '22 22:12

Alexander Teut


1 Answers

your command should use

  • shell=True since it's using 2 commands chained by an exit condition test
  • cwd=your_directory
  • status check

like this:

from subprocess import call
status = call("mvn clean && mvn compile",cwd="/users/foo/xxx",shell=True)

Personally I tend to avoid depending on shell=True. In those cases I tend to decompose both commands and put arguments directly as argument list so if some nasty whitespace slips in it is quoted automatically:

if call(["mvn","clean"],cwd="/users/foo/xxx") == 0:
    status = call(["mvn","compile"],cwd="/users/foo/xxx")

Note that if you want to get hold of the commands output from the python side (without redirecting to a file, which is dirty), you'll need Popen with stdout=PIPE instead of call

like image 73
Jean-François Fabre Avatar answered May 13 '23 13:05

Jean-François Fabre