简体   繁体   中英

Passing variables from PHP to python

I have a python script. When I run the script from the command line as:

python upgrade.py arg1 arg2

The script runs successfully. Now I am trying to pass the same variables via PHP code using:

passthru("python upgrade_device.py $arg1 $arg2");

The script does not execute. I am accepting the arguments using:

sys.argv

The arguments are passed correctly I have tested using print

This is specific command where the execution fails:

child=pexpect.spawn('ssh admin@%s'%ip_addr)

ip_addr is one of the arguments passed from PHP. Right below this command I am ip_addr so as to find what value is passed to the command. and the value is as expected.

I have the ip_addr variable stored correctly. I have even type casted it to string so that should not be problem.

In general, is there a difference of format in passing variables from the command line and passing from PHP

For my understanding i think passing it through shell and php is the same, i can't be sure for 100% but that what i know from experience.

For your case if you have verified with print that it's the right string to pass (mean take the output and test it in the terminal if it work) if it work, than verify if the python script file is in the same directory as the php script file , because the shell will be opened at the current php script path . And so the shell command should respect that . For example let assume php script file is in the root "/" , and python script file is in "/myPythonScripts/imageProccessing/" then when you execute something like "python myPyScript.py 646545645" for example, in this example in php you should execut "python ./myPythonScripts/imageProccessing/myPyScript.py 646545645" , as i said the shell is launched on the php script path.

Now if that's not the problem, then try escaping the string first , with escapeshellcmd() . And see what it give. There is characters that are not supported by the shell, or that have a certain signification and parsed by the shell differently . make sure none of them is passed as argument.

In case none of the above is helpful try to use execshell() instead, and see what it give. Too probable that will not make a difference.

Edit: In case nothing helped, try to change just a bit the way of the exchange is done, and use the way it's done in this response using json https://stackoverflow.com/a/14048046/7668448 (it's a kind of more convenient)

Please if any of that solved the problem, precise in a response which one was! I hope it will help. Also if it's not your case it may be useful for other persons in the future. Think also about giving the solution when you do! (i also personally interested too)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM