PHP exec cannot execute Python script - python

I use PHP in Windows 11. I cannot execute Python script in PHP exec.
The current situation is as follows, Commands that do not call Python scripts can be executed:
exec("cd E:/Python/WordFrequency && ipconfig", $output, $result_code);
exec("Python -V", $output, $result_code);
The above two lines of code return code 0.
However, the following code returns code 1:
exec("Python E:/Python/Mnist/main.py", $output, $result_code);
Run directly in Windows PowerShell:
Python E:/Python/Mnist/main.py
There is no problem.
However, calling in PHP returns code 1.
What's the matter, please?

After hard work, I have solved this problem a few days ago. Now, I put the solution here.
The reason why PHP cannot call Python files is that when executing the following command in exec():
Python E:/Python/Mnist/main.py
The following error was returned:
RuntimeError: Could not determine home directory.
After further testing, it was found that:
import os
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
It is found that PHP can successfully call Python if main.py contains only the above five lines of code. This means that my entire PHP and Python program logic and operating system permissions are all right.
And once I add another line of code:
from matplotlib import pyplot as plt
PHP will not be able to call Python successfully, and will prompt the error message "Could not determine home directory". This means the error introduced by the code from matplotlib import pyplot as plt.
At the beginning, I thought there was a problem with the path or permissions of matplotlib installation. After inspection, there are no problems.
After inquiring more information, I gradually understood the reason. For the module matplotlib, it will ask to determine the user's home directory. Because usually only the users of the operating system call the matplotlib module, which is meaningful and won't cause trouble. However, unspecified visitors who call Python scripts through browsers will not own or determine the user's home directory. Therefore, in this case, it is very reasonable for the matplotlib module to throw an error that cannot determine the user's home directory.
How to solve the problem of Could not determine home directory?
The method is to add the following code before the line from matplotlib import pyplot as plt (or directly at the beginning of the Python file):
import os
os.environ['HOMEPATH'] = 'E:/Python/Mnist'
That is, the home directory of the unspecified user who accesses the Python script through the browser is manually specified. So as to provide matplotlib with a place where necessary files can be saved.

Related

Asking for overwrite while trying to run script in ipython

I am fairly new to programming in python. I installed anaconda and am running iPython (the Jupyter qtconsole) v.4.3.0 and python v.3.6 on a Mac. Currently, I am trying to import a module with functions located in my home directory.
I have looked at stackoverflow and python documentation and found that it could be done with:
%run "Users/myUser/python_functions.py"
or
import python_functions
However, when I try both of these approaches, I get prompted to overwrite the file that I am running or importing:
File `python_functions.py` exists. Overwrite (y/[N])?
This is changing the previous file and not getting the functions I want to be imported.
What may explain this, and what can I do to import my module?
this is wrong but leaving it up for shame
import on ubuntu (and I'm guessing many other unix-like OSs including Mac) is a utility that saves any visible window on an X server and outputs it as an image file. You can capture a single window, the entire screen, or any rectangular portion of the screen.
My guess if you are running the import command in your console, and it's about to take a screenshot and save it over an existing file - python_functions
Before you the use the python import command, start a python interpreter:
$ python
>>>import yourfile
edit: on re-reading your question, I'm not so sure about my guess anymore, but leaving it up until you tell me I'm wrong :)
Running Jupyter qtconsole as an interpreter is likely causing the problem in this scenario. Instead using a IDE or command line interpreter will resolve it .
Since anaconda was installed, trying it with the IDE Spyder executes the code just fine without the overwrite prompt. It works on others (e.g PyCharm, Rodeo, etc.) as well.

Python 3.5.1 in Anaconda 3 from JetBrains PyCharm IDE - environment objects

I am coming into Python from R, and installed Python 3.5 with Anaconda. Now, PyCharm console has a prompt identical to an iPython Notebook, i.e. instead of >>>, it shows [1] at the command line.
After writing a toy line of code (below) in a .py document, and running it from within PyCharm, showing no errors, I was under the assumption that the function toss(), which was defined in the .py document would be ready to use in the console. However this did not seem to be the case. I ended up copying and pasting the pertinent lines of code on the console, entering, and then, finally, the function toss() was accessible to produce random examples of the roll of a die.
Logically, there has to be a smoother way of moving code from a .py file in the Editor to the environment accessible from the Python Console. But this shorter way doesn't seem to be simply running the .py file.
Code:
import random
def toss():
return(random.randint(1,6))
So how do you make the code in a Python file in the Editor accessible in the local environment?
You need to import it first. Let's say that your function toss() is in a file called foo.py then that means that you can do
from foo import toss
toss()
in your Python Console to use your function. A Python source file is, by definition, a module and you'll need to import it in order to use any functions defined there.

Start ipython notebook with predefined imports [duplicate]

I'm trying to to auto load the division module from __future__ on startup,
i've currently got a simple script in the IPython startup libray with the line:
from __future__ import division
which works fine when run directly from the shell,
however, the module does not appear to load when the line is run from the script,
i made sure that the startup script is loaded by adding some arbitrary variable assignments to it:
from __future__import division
x=1
y=2
and the variables were preassigned when IPython was launched (as expected).
I've tried looking at some solutions here and here but got nowhere,
any help would be appreciated,
thanks
i've found a solution to this one, in your IPython profile directory (by default - .ipython\profile_default), edit the file ipython_config.py (create it with ipython profile create if it does not exist) with the following lines:
# loads the root config object
c=get_config()
# executes the line in brackets on program launch
c.InteractiveShellApp.exec_lines = ['from __future__ import division']

How do I load and run specific packages when I launch 'matplotlib'?

I see how to change certain settings for matplotlib in such a way that the are used to configure it each time I launch, including when I launch interactively with
ipython --pylab
but I'm not sure how run arbitrary code each time I launch in this way, or how to ensure that certain packages have been imported. For example I'd like to do the following whenever I launch as above:
from mpltools import style
style.use('ggplot')
How do I load and run specific packages when I launch 'matplotlib'?
From the ipython website it seems you can place any .py file in the startup folder of your profile and it will be run when ipython is initiated. For help finding the profile where your startup folder is [see here].
To get the effect your looking for you need to check that matplotlib has been imported, the only way I can think of doing that is to add the following
import sys
if "matplotlib" in sys.modules:
# Do something
print
print "This seems to be working"
I have left it with the test so you can quickly determine if it is working.
Two things to note: I am using ipython 2.0.0-dev (in case this has any bearing), and secondly I suspect that calling sys.modules is not recommended, or at least that was the impression I had off the SO post I borrowed the idea from, perhaps someone better than I can enlighten us.

Automatically import modules when entering the python or ipython interpreter

I find myself typing import numpy as np almost every single time I fire up the python interpreter. How do I set up the python or ipython interpreter so that numpy is automatically imported?
For ipython, there are two ways to achieve this. Both involve ipython's configuration directory which is located in ~/.ipython.
Create a custom ipython profile.
Or you can add a startup file to ~/.ipython/profile_default/startup/
For simplicity, I'd use option 2. All you have to do is place a .py or .ipy file in the ~/.ipython/profile_default/startup directory and it will automatically be executed. So you could simple place import numpy as np in a simple file and you'll have np in the namespace of your ipython prompt.
Option 2 will actually work with a custom profile, but using a custom profile will allow you to change the startup requirements and other configuration based on a particular case. However, if you'd always like np to be available to you then by all means put it in the startup directory.
For more information on ipython configuration. The docs have a much more complete explanation.
Use the environment variable PYTHONSTARTUP. From the official documentation:
If this is the name of a readable file, the Python commands in that
file are executed before the first prompt is displayed in interactive
mode. The file is executed in the same namespace where interactive
commands are executed so that objects defined or imported in it can be
used without qualification in the interactive session.
So, just create a python script with the import statement and point the environment variable to it. Having said that, remember that 'Explicit is always better than implicit', so don't rely on this behavior for production scripts.
For Ipython, see this tutorial on how to make a ipython_config file
I use a ~/.startup.py file like this:
# Ned's .startup.py file
print("(.startup.py)")
import datetime, os, pprint, re, sys, time
print("(imported datetime, os, pprint, re, sys, time)")
pp = pprint.pprint
Then define PYTHONSTARTUP=~/.startup.py, and Python will use it when starting a shell.
The print statements are there so when I start the shell, I get a reminder that it's in effect, and what has been imported already. The pp shortcut is really handy too...
As a simpler alternative to the accepted answer, on linux:
just define an alias, e.g. put alias pynp='python -i -c"import numpy as np"' in your ~/.bash_aliases file. You can then invoke python+numpy with pynp, and you can still use just python with python. Python scripts' behaviour is left untouched.
While creating a custom startup script like ravenac95 suggests is the best general answer for most cases, it won't work in circumstances where you want to use a from __future__ import X. If you sometimes work in Python 2.x but want to use modern division, there is only one way to do this. Once you create a profile, edit the profile_default (For Ubuntu this is located in ~/.ipython/profile_default) and add something like the following to the bottom:
c.InteractiveShellApp.exec_lines = [
'from __future__ import division, print_function',
'import numpy as np',
'import matplotlib.pyplot as plt',
]
You can create a normal python script as import_numpy.py or anything you like
#!/bin/env python3
import numpy as np
then launch it with -i flag.
python -i import_numpy.py
Way like this will give you flexibility to choose only modules you want for different projects.
As ravenac95 mentioned in his answer, you can either create a custom profile or modify the default profile. This answer is quick view of Linux commands needed to import numpy as np automatically.
If you want to use a custom profile called numpy, run:
ipython profile create numpy
echo 'import numpy as np' >> $(ipython locate profile numpy)/startup/00_imports.py
ipython --profile=numpy
Or if you want to modify the default profile to always import numpy:
echo 'import numpy as np' >> $(ipython locate profile default)/startup/00_imports.py
ipython
Check out the IPython config tutorial to read more in depth about configuring profiles. See .ipython/profile_default/startup/README to understand how the startup directory works.
My default ipython invocation is
ipython --pylab --nosep --InteractiveShellApp.pylab_import_all=False
--pylab has been a ipython option for some time. It imports numpy and (parts of) matplotlib. I've added the --Inter... option so it does not use the * import, since I prefer to use the explicit np.....
This can be a shortcut, alias or script.
I created a little script to get ipython initialized with the code you want.
Create a start.ipy file at your project root folder.
Edit the created file with all the things you need to get into ipython.
ipython profile create <your_profile_name>. Tip, do not add the word "profile" to the name because ipython already includes it.
cp start.ipy ~/.ipython/profile_<your_profile_name>/startup/start.ipy
Run ipython --profile=<your_profile_name> everytime you need everything loaded in ipython.
With this solution, you don't need to set any env variable up. You will need to copy the start.ipy file to the ipython folder every time you modify it, though.

Categories

Resources