I have the following python script test.py:
import subprocess
subprocess.call(["php", "C:/Documents and Settings/user/My Documents/Downloads/load_data.php"])
the idea is to run another php script in which I make a LOAD DATA INFILE to a MySQL table, but it generates the following error:
Traceback <most recent call last>:
File "test.py", line 3, in <module>
subprocess.call<["php","load_data.php"]>
File "C:\Python34\lib\subprocess.py", line 537, in call
with Popen<*popenargs, **kwargs> as p:
File "C:\Python34\lib\subprocess.py" line 859, in __init__
restore_signals, start_new_session>
File "C:\Python34\lib\subprocess.py", line 1114, in _execute_child startupinfo>
FileNotFoundError: [WinError 2] The system cannot find the file specified
If I run the direct load_data.php script in a web browser, it works without any problem so it seems to me that the problem is in python, it is worth mentioning that I have done this correctly before but with python 3.6, some idea if I need it configure something or add a library.
I have php5.3, apache 2.2.21, mysql5.5.20, python3.4, I tried to put the absolute path of the PHP script but is the same
Regards!
For run PHP with Python, you must add the full path to the PHP executor and the full path of the file to execute.
Example :
import subprocess
subprocess.call(["C:\\wamp64\\bin\\php\\php5.3\\php.exe", "C:\\Documents and Settings\\user\\My Documents\\Downloads\\load_data.php"])
Don't forget to escape the anti-slashes, Otherwise the subprocess will not work and there will be no visible error.
Related
I am trying to run a php script that will call a python script that calls imaplib to pull some files from my email. When I run the python script standalone in vscode (bash terminal), it works as designed. When I run the PHP script that calls the python script, the following error is produced.
Traceback (most recent call last):
File "C:/xampp/htdocs/report/pythonfile/parse_script_og.py", line 43, in <module>
mail = imaplib.IMAP4_SSL('imap.googlemail.com')
AttributeError: module 'imaplib' has no attribute 'IMAP4_SSL'
As a test, I echoed out the command and pasted it into Git Bash. The files were pulled and added to the folder specified. When I pasted the command into CMD, the error above was produced. What settings am I missing?
I am using XAMPP, VSCode, PHP 7.3.4, Python 3.7.1
From recommendation below I added "import ssl" to my python script, I received the following error:
"Traceback (most recent call last):"
" File "C:/xampp/htdocs/report/pythonfile/parse_script_og.py", line 2, in <module>"
" import ssl"
" File "C:\Users\Garrett\Anaconda3\envs\snowflakes\lib\ssl.py", line 98, in <module>"
" import _ssl # if we can't import it, let the error propagate"
"ImportError: DLL load failed: The specified module could not be found."
so then I went to my python environment, and tried to "pip install ssl" and I got the following error.
(snowflakes) C:\Users\Garrett>pip install ssl
Collecting ssl
Using cached https://files.pythonhosted.org/packages/83/21/f469c9923235f8c36d5fd5334ed11e2681abad7e0032c5aba964dcaf9bbb/ssl-1.16.tar.gz
ERROR: Complete output from command python setup.py egg_info:
ERROR: Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\Garrett\AppData\Local\Temp\pip-install-abzxmk8x\ssl\setup.py", line 33
print 'looking for', f
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print('looking for', f)?
----------------------------------------
ERROR: Command "python setup.py egg_info" failed with error code 1 in C:\Users\Garrett\AppData\Local\Temp\pip-install-abzxmk8x\ssl\
(snowflakes) C:\Users\Garrett>
Another Update
The following command is what is executed in PHP (exec()). The input folder will contain files pulled from email. The output folder will contain a singular file created from the files pulled from email. If I paste this command into GitBash, everything works as planned. If I paste the following command into CMD, I get the error shown above.
C:/Users/Garrett/Anaconda3/python.exe C:/xampp/htdocs/report/pythonfile/parse_script_og.py C:/xampp/htdocs/report/input/ C:/xampp/htdocs/report/output/out.csv John Doe 06-Jan-2018 16-Jan-2019
IMAP4_SSL is only present if Python's ssl module is available (you can test with import ssl). Try upgrading your server's python version, and/or installing the ssl module.
https://docs.python.org/3/library/ssl.html
EDIT 1:
There’s also a subclass for secure connections:
class imaplib.IMAP4_SSL(host='', port=IMAP4_SSL_PORT, keyfile=None, certfile=None, ssl_context=None)
This is a subclass derived from IMAP4 that connects over an SSL encrypted socket (to use this class you need a socket module that was compiled with SSL support).
If host is not specified, '' (the local host) is used. If port is omitted, the standard IMAP4-over-SSL port (993) is used. ssl_context is a ssl.SSLContext object which allows bundling SSL configuration options, certificates and private keys into a single (potentially long-lived) structure. Please read Security considerations for best practices.
keyfile and certfile are a legacy alternative to ssl_context - they can point to PEM-formatted private key and certificate chain files for the SSL connection. Note that the keyfile/certfile parameters are mutually exclusive with ssl_context, a ValueError is raised if keyfile/certfile is provided along with ssl_context.
Changed in version 3.3: ssl_context parameter added.
Changed in version 3.4: The class now supports hostname check with ssl.SSLContext.check_hostname and Server Name Indication (see ssl.HAS_SNI).
Deprecated since version 3.6: keyfile and certfile are deprecated in favor of ssl_context. Please use ssl.SSLContext.load_cert_chain() instead, or let ssl.create_default_context() select the system’s trusted CA certificates for you.
https://docs.python.org/3/library/imaplib.html
EDIT 2:
you have to use full path for the python and for your file. you may find the former from the which python command, that most likely outputs '/usr/bin/python' and you should already know the latter. so your command would look like this:
$mystring = exec('/usr/bin/python /home/user/testing.py');
and you should make sure your python script has all appropriate permissions, because your web-server most probably is running as a different user, so permissions should be "-rwxrwxr-x" or something close.
Python Script Failing to Execute from PHP exec()
I'm trying to run a Python script from PHP using the following command:
$cmd="sudo /var/www/html/test/class.sh /tmp/tib.jpg"
exec($cmd,$output,$return)
So, i write the command into a shell script "class.sh"
cd $my_work_dir
/usr/bin/python3 -m src.inference.classify file $1
But, i can run the script in command line "php /var/www/html/test/class.sh", but that can't run in the browser with output. I use the proc_open capture the part of error:
array ( 'stdout' => '', 'stderr' => 'Traceback (most recent call last): File "/usr/lib/python3.4/runpy.py", line 170, in _run_module_as_main "__main__", mod_spec) File "/usr/lib/python3.4/runpy.py", line 85, in _run_code exec(code, run_globals) File "/home/bmk/1\\udce6\\udc96\\udc87\\udce6\\udca1\\udca3/0\\udce7\\udca0\\udc94\\udce5\\udc8f\\udc91/Dog/Dog-AI/dog-breeds-classification-master/src/inference/classify.py", line 7, in import tensorflow as tf File "/usr/local/lib/python3.4/dist-packages/tensorflow/__init__.py", line 24, in from tensorflow.python import * File "/usr/local/lib/python3.4/dist-
I think , because,Python can not locate my python library.
I also refered another stackoverflow Running a Python script from PHP , that is not work for me.
Can anybody help me?
try
File name should be in path of the php directory i.e where the index.php is present
$a = exec_shell("python filename.py");
Output of $a will be the output of the file.
With exec you can execute php code.
And just include your libary in the right way in the phyton file (maybe fully qualified path name)?
if you want to execute an phyton script form php:
<?php
$runcommand= escapeshellcmd('/usr/custom/test.py');
$output = shell_exec($runcommand);
echo $output;
?>
I have a python code which runs in my terminal and prints the result. I wrote a php code which executes the python code using exec("python example.py argument_1"). The php code also prints the result while executing it from the terminal.
But when I try to call the php from the browser (or) through a curl request, the result of the php is not being displayed. Apache error log displays the following message.
Traceback (most recent call last):
File "./example.py", line 3, in <module>
from lxml import etree
ImportError: No module named lxml
Kindly look into this issue.
Solution :
I had conflict with the python versions
exec("/usr/local/bin/python example.py argument_1") has resolved my issue
I think you can print the sys.path(modules will be fond by python via those path ) for more details. you maybe develop your code in linux.
In linux, each user has different sys.path.
for example, I use root to run python to get sys.path in python,
'/usr/bin',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/usr/lib/python2.7/lib-old',
'/usr/lib/python2.7/lib-dynload',
'/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages/PILcompat',
'/usr/lib/python2.7/dist-packages/gtk-2.0',
'/usr/lib/python2.7/dist-packages/ubuntu-sso-client',
'/usr/lib/python2.7/dist-packages/IPython/extensions']
use an other user to get sys.path in python
['',
'/home/mahome/anaconda2/bin',
'/home/mahome/anaconda2/lib/python27.zip',
'/home/mahome/anaconda2/lib/python2.7',
'/home/mahome/anaconda2/lib/python2.7/plat-linux2',
'/home/mahome/anaconda2/lib/python2.7/lib-tk',
'/home/mahome/anaconda2/lib/python2.7/lib-old',
'/home/mahome/anaconda2/lib/python2.7/lib-dynload',
'/home/mahome/anaconda2/lib/python2.7/site-packages',
'/home/mahome/anaconda2/lib/python2.7/site-packages/Sphinx-1.4.1-py2.7.egg',
'/home/mahome/anaconda2/lib/python2.7/site-packages/setuptools-23.0.0-py2.7.egg',
'/home/mahome/anaconda2/lib/python2.7/site-packages/IPython/extensions',
'/home/mahome/.ipython']
so, you maybe use different user to execuate your code.
Hi I've got the following written in a python script pythonscript1.py in linux debian in the directory /home/user/a/:
import subprocess
subprocess.call(["python" /home/user/b/phpcall.py"])
where the phpcall.py script contains:
import subprocess
subprocess.call(["php", "/home/user/b/phpscript1.php"])
individually called from console all scripts function perfectly, but when I use the first script whilst the 2nd script calls/looks for a file in directory b, rather than a, It yields the following error:
"PHP warning: include_once(something.php): failed to open stream: no such file in /home/user/b/phpschript1.php on line 25
Now it is quite clear to me the problem is that it cannot reach out of it's original directory. But I don't know what command I should add to the first script to allow the 2nd script to look in folder b.
So far google results have suggested something with "include_path='include'" but I don't know how/where to incorporate the statement succesfully.
Any suggestions on the correct syntax would be appreciated!
you can try this program:
import subprocess
import sys
proc = subprocess.Popen(
[sys.executable, '/home/user/b/phpcall.py'],stdin=subprocess.PIPE)
proc.communicate()
i think it's work. if not let know.
If the php script works only if you start it from the directory with the python script then you could use cwd parameter to change the working directory for the subprocess:
#!/usr/bin/env python
from subprocess import check_call
check_call(["php", "/home/user/b/phpscript1.php"], cwd="/home/user/b")
I've added the shebang #!/usr/bin/env python so that you could run the script directly as /path/to/phpcall.py assuming it is executable (chmod +x phpcall.py).
Note: if you want to run the python script as user user then you could specify the path using ~:
#!/usr/bin/env python
import os
from subprocess import check_call
script_dir = os.path.expanduser("~/b")
check_call(["php", os.path.join(script_dir, "phpscript1.php")], cwd=script_dir)
To avoid hardcoding the script directory, you could find it dynamically:
#!/usr/bin/env python
import os
from subprocess import check_call
script_dir = get_script_dir()
check_call(["php", os.path.join(script_dir, "phpscript1.php")], cwd=script_dir)
where get_script_dir().
For future reference the code that directly called the php script from python within was:
import os
os.chdir("/home/user/b")
os.system("php /home/user/b/phpscript1.php")
.Thanks Marc B
& I love the dynamic approach Sebastian, thank you :)
When I attempt to execute a Python script I have, which (if it's relevant) is importing pymssql, I get the error:
Traceback (most recent call last): File "./assets/bin/invoices", line 4, in import pymssql as db ImportError: dlopen(/Library/Python/2.7/site-packages/pymssql.so, 2): Symbol not found: _iconv Referenced from: /usr/local/lib/libsybdb.5.dylib Expected in: /Applications/MAMP/Library/lib/libiconv.2.dylib in /usr/local/lib/libsybdb.5.dylib
I'm attempting to execute it using shell_exec, after explicitly setting the environment variables PATH and LD_LIBRARY_PATH to match their values when queried from the shell. Does anyone know why this is happening, and/or how to make it work as expected? This has stumped me for day.