Calling a subprocess in python with environmental

2020-07-13 07:49发布

问题:

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.

回答1:

As jordanm noted in his comment:

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