Skip to content Skip to sidebar Skip to footer

How To Pass A List Variable To Subprocess.call Command In Python

I have a list apps = [] apps.append('wq35a5huqlja45jsyukrpmwuiayovrmh') apps.append('q7mimvgduueernwvw4y22t5huemykntw') apps.append('pmudbpyquna2bll53pwqh7gdejxtmchq') I want to p

Solution 1:

subprocess.call(["service", "delete", *apps])

will expand to

subprocess.call(["service", "delete", "wq35a5huqlja45jsyukrpmwuiayovrmh", ...])

Solution 2:

subprocess.call("service delete $apps", shell=True)

This is wrong because apps is not a shell variable. Passing a python string variable works out of the box.

In[12]:daemon='ntp'In[13]:sb.call(["service",daemon,"status"])ntp.service - LSB:StartNTPdaemonLoaded:loaded(/etc/init.d/ntp;bad;vendor preset:enabled)Active:active(running)sinceMon2019-03-04 01:37:43 IST;1day13hagoDocs:man:systemd-sysv-generator(8)Process:2045 ExecStart=/etc/init.d/ntpstart(code=exited,status=0/SUCCESS)Tasks:1Memory:2.1MCPU:6.816sCGroup:/system.slice/ntp.service└─2345/usr/sbin/ntpd-p/var/run/ntpd.pid-g-u123:130Warning:Journalhasbeenrotatedsinceunitwasstarted.Logoutputisincompleteorunavailable.Out[13]:0

However to pass anything other than strings you would have to manually do some type conversion, so for lists you would have to do something like this.

>>>a = ['a', 'b', 'c']>>>sb.call(["echo", ','.join(a)])
a,b,c
0

Solution 3:

I upvoted Harly H's answer, but just for completeness, here's another way.

subprocess.run(['xargs', '-0', 'service', 'delete'],
    input='\0'.join(apps)),
    check=True,   # probably a good idea, but not strictly required
    universal_newlines=True)

This requires a Python new enough to have subprocess.run() though something similar is easy or at least possible even with the Python 2 subprocess interface. In 3.7+ universal_newlines is more aptly labelled text.

xargs will also take care of avoiding any "argument list too long" errors if apps is a really long string. (Google for ARG_MAX.)

Post a Comment for "How To Pass A List Variable To Subprocess.call Command In Python"