0

I need to pass the argument with variable name from PHP to PYTHON.

here is my requirement in coding.

$output = shell_exec('python3 ActorArrayMatcher_FS2.py var1 = val1 & var2 = val2 & ... & varN = valN ');
print_r($output);

and how to receive in python

import sys
print(sys.argv)

Please share the knowledge. Thanks in advance.

Avz Vicky
  • 11
  • 9

2 Answers2

0

shell_exec() is a bash (or other interpreter) call, so you'll need to structure your command as if you were running it on the command line:

$output = shell_exec('python3 ActorArrayMatcher_FS2.py var1=val1 var2=val2 varN=valN');

Things to keep in mind:

  • python3 must be executable by the user running your PHP script
  • Ensure you escape any variable shell arguments via escapeshellarg() before passing them into shell_exec()
  • The path to ActorArrayMatcher_FS2.py would be safer as an absolute path, and you'll need to ensure that the user running your PHP script has permissions for it
scrowler
  • 24,273
  • 9
  • 60
  • 92
  • sorry. Did not understand what i am asking. how to pass the parameter with variable name and how to receive in python. var1=val1 var2=val2 varN=valN how to pass should like this and import sys print(sys.argv) receive like this – Avz Vicky Oct 19 '18 at 11:19
  • Does your python script receive the input variables from `sys.argv`? – scrowler Oct 19 '18 at 11:38
0

You'll have to iterate over sys.argv, it is a list:

#!/usr/bin/env python
import sys


def main():
    for a in sys.argv:
        print(a)


if __name__ == '__main__':
    main()

For more elaborate argument parsing, I suggest you look at argument parsing libraries for Python; in no special order:

Relevant SO question: What's the best way to parse command line arguments?

Oliver Baumann
  • 2,209
  • 1
  • 10
  • 26