0

I have to run a shell command from python and get the output of that command into a python variable

python_var = subprocess.check_output('/opt/PPPP/QQQ/my_cmd -option1 -option2 /opt/XXXX/YYYY/ZZZZZ/my_file')
Tomerikoo
  • 15,737
  • 15
  • 35
  • 52
  • /opt/PPPP/QQQ/my_cmd -option1 -option2 /opt/XXXX/YYYY/ZZZZZ/my_file --------- i want to run the command my_cmd with option option1,option2 and will process the file my_file from some path. produced output want to store in variable python_var – Rakesh Kushwaha Jul 23 '19 at 11:39
  • 3
    And.... what seems to be the problem/question? – Tomerikoo Jul 23 '19 at 11:40
  • 1
    passing a string requires `shell=True` on Linux. Or pass arguments as a list (recommended) – Jean-François Fabre Jul 23 '19 at 11:41
  • read more about [check_output](https://docs.python.org/2/library/subprocess.html#subprocess.check_output) (Python 2.7) – Tomerikoo Jul 23 '19 at 11:44

1 Answers1

0

You need to hand-split the arguments into a sequence, not just pass a string (passing a whole string requires shell=True on Linux, but introduces all sorts of security/stability risks):

python_var = subprocess.check_output(['/opt/PPPP/QQQ/my_cmd', '-option1', '-option2', '/opt/XXXX/YYYY/ZZZZZ/my_file'])
ShadowRanger
  • 124,179
  • 11
  • 158
  • 228