How to execute Python script in PHP

Source: Internet
Author: User
How do I execute Python script in PHP?
You want to SSH to the remote server via PHP, then execute a python file on the server, get the results, and print from PHP.
My code is as follows:

$connection = Ssh2_connect (' remote-server ', 22);
Ssh2_auth_password ($connection, ' root ', ' pwd ');

$string = ssh2_exec ($connection, ' Python pythonfile.py; sleep 20 ');
Stream_set_blocking ($string, true);
echo stream_get_contents ($string);


But the null value is printed in PHP.
If I put
$string = ssh2_exec ($connection, ' Python pythonfile.py; sleep 20 ')
Replaced by
$string = ssh2_exec ($connection, ' ls-l ')
There is no problem, the program output normally.

The python file on the remote server typically takes 15 seconds to run, so I set sleep 20, but I still get no results.
Want to ask if the code is wrong? How to correct it? PHP Python SSH2

Share to:


------Solution--------------------
References:
solved, I changed the code again.
$stream = ssh2_exec ($connection, ' CD dca_automation/main/qautilities/utils; python cluster_discovery.py ');
Stream_set_blocking ($stream, true);

$string = Stream_get_contents ($stream);
Echo $string;

No longer output Python results to a file, let $stream get it directly, because "in non-blocking mode a fgets () call would always return right away while in blocking mode It will wait for data to become available on the stream ", so, if the previous code, once the Output.txt file generation, even if the results have not been written up, $stream have obtained data, so Strea M_set_blocking () will automatically terminate. But if I write the result of the python directly onto the stream, the result is not fully generated before the process will block.
I don't know what I'm explaining, right? The inappropriate place welcomes everyone to correct me.


No mistake, it is the stream that receives the data returned by the shell, triggering the stream to return the result, thus executing the stream_get_contents
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.