Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a subprocess in python with environmental variables

I am trying to write a python script to automatically scan a section of plex using the Plex Media Scanner. To do so, I must run the scanner as the user running plex (in this case it is 'plex') as well as provide it with the environment variable 'LD_LIBRARY_PATH'. I've tried using both subprocess.call and subprocess.Popen with no difference. In either case, I am not getting any output. Here is the code I am using:

#!/usr/bin/python
import os
import subprocess
import shlex

env = os.environ.copy()
env['LD_LIBRARY_PATH'] = '/usr/lib/plexmediaserver'
s = "/bin/su - plex -c '/usr/lib/plexmediaserver/Plex\ Media\ Scanner -s -c 2'"
task = shlex.split(s)
exitCode = subprocess.call(task, env=env, shell=True)

Now I already have a working version that does what I want it to do but I had to resort to using a wrapper bash script to do so. You can see the code below:

#!/bin/sh
export LD_LIBRARY_PATH=/usr/lib/plexmediaserver
/usr/lib/plexmediaserver/Plex\ Media\ Scanner $@

And the relevant line of the script which calls it:

exitCode = subprocess.call("/bin/su - plex -c '/var/lib/deluge/delugeScripts/pms.sh -s -c 2'", shell=True)

Thanks for your help.

like image 568
pyarmak Avatar asked Jan 07 '14 05:01

pyarmak


People also ask

How do you call a subprocess in Python?

To start a new process, or in other words, a new subprocess in Python, you need to use the Popen function call. It is possible to pass two parameters in the function call. The first parameter is the program you want to start, and the second is the file argument.

How can we avoid shell true in subprocess?

From the docs: args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names).

What is difference between subprocess Popen and call?

Popen is more general than subprocess. call . Popen doesn't block, allowing you to interact with the process while it's running, or continue with other things in your Python program. The call to Popen returns a Popen object.

Does subprocess Popen block?

Popen is nonblocking. call and check_call are blocking. You can make the Popen instance block by calling its wait or communicate method.


1 Answers

As jordanm noted in his comment:

the - in su makes it a login shell which re-initializes the environment.

like image 80
pyarmak Avatar answered Oct 15 '22 08:10

pyarmak