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']
Related
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.
I am trying to run this GitHub project in python, but I could only run it using the Terminal of Pycharm IDE.
According to the guide from the GitHub repository, I removed the $ sign from the beginning of $ python train.py RGCN PPI and could run it there. What does $ mean here and how can I run a file like this in Python Console (for example after >>> sign)?
The '$' isn't part of Python's syntax, it's a visual cue in the documentation representing the command prompt.
To answer the question from the title of this post, I'll provide some
instructions first on how to load scripts into the Python console.
However, for your specific case, you don't need this. Scroll down to
the part about debugging in PyCharm.
There's two ways you can get your script into the console. One is to simply load it using the right version of the two lines I give right below, or you can load it as a module - even if it wasn't intended to be one.
In general, to execute a script in the Python shell on Python 2 you can do
>>> execfile(r"<path to script here>")
On Python 3 it's more verbose:
>>> exec(open(r"<path to script here>").read())
The effect this has is as if you cut-n-pasted the script into the console. The console's global scope will get all the functions, classes, and variables that are leftmost indented in the file. Also it might not run your if __name__ == '__main__': block. But you could hack that.
If you want the vars/classes/etc to be put in another scope than your console's global scope, then there are two additional parameters to the above commands. The first one is a dictionary for the globals , and one for the locals. You can get away with only supplying the globals parameter - it's just an ordinary dictionary object you need.
If the file you want to load is a module, you could import it as you would any other module by appending its home folder to the Python module search path, and using the import directive. You can load your script this way even if it wasn't intended to be module.
>>> import sys
>>> sys.path.append(r'/Users/todd/projects/mymodule_folder')
>>> import mymodule
If you make modifications to it and want to reload it:
>>> import importlib
>>> importlib.reload(mymodule)
Loading your script as a module avoids polluting your console's global scope. After it loads, just prefix the names of your script's functions and variables with the module name. The module name will be the name of the file without the .py extension.
If the script requires command line options, you could just hard code values for those into the script and disable lines of code that try and get values from the CLI. If it gets complicated, consider running it in an IDE as described in the next section.
So the above is how you can run your python scripts in whatever Python REPL console you want.
BUT loading your scripts into the Python console may not be at all
required for your purposes. You wanted to debug some scripts (train.py,
test.py) from this project:
https://github.com/microsoft/tf-gnn-samples).
Debugging Command Line Script With PyCharm
In many cases, a Python script is written to run from the OS shell and take command line options from the user. These kinds of script could be loaded into the Python console, but most require some minor hacks to run. However, if all you want to do is debug such a script, you don't need to muck with the console.
PyCharm supports running these as is (as does Eclipse and other IDEs) like any other script. It's just a matter of creating a run/debug configuration for the project. I just installed PyCharm and gave it a try in order to record the details. Easy task.
Just open the project in PyCharm, and above the editor pane, on the toolbar, there's a menu option for Edit Configurations. Click that to open the Run/Debug Configurations dialog and click the + to add a configuration. A small dialog will appear with predefined templates - select Python as your template and accept.
Then in the main dialog, fill in Script path: with the path to train.py (or another script), then click the checkbox, [x] Emulate terminal in output console. Also, you can add command line options in the Parameters: text box (I put in the text: mymodel mytask just to satisfy the script's need for two parameters). Click OK at the bottom to accept the configuration and shut the dialog.
Now you should see a green bug icon on the toolbar.Set a breakpoint in the __main__ block of the script and click the debug icon to start debugging the script. That should do it!
Debugging Python Command Line Script with PDB
PDB - the Python Debugger can be run without an IDE. This is another way to debug a script of any sort. If it requires command line parameters, provide them from the OS shell when you start the debugger:
$ pdb myscript.py mymodel mytask
That's really all there is to starting a debug session. PDB requires some knowledge of its text based commands. After starting a session, you can get a listing of code near the current line of execution by entering l. Enter help to see a listing of the commands.
To step one line of execution, enter 's' for step, or enter 'step'. To set a breakpoint, enter break <line-number>, or set a breakpoint on an expression. A reference on the commands available can be found here: https://docs.python.org/2/library/pdb.html . There are also plenty of versions of pdb cheatsheets available online - just google "pdb cheatsheet" and select one.
I am trying to set a breakpoint in an external Python module in VS code.
I have tried editing the source file and inserting import pdb; pdb.set_trace() where I want the breakpoint.
This enters the pdb command line debugger rather than the debugger in the VS Code GUI.
How do I set a breakpoint in an imported Python module so that I enter the VS Code debugger?
Marvin's suggestion appears to be sufficient:
add a launch configuration "justMyCode":false .
See code.visualstudio.com/docs/python/debugging#_justmycode
You need to import the folder containing the source code of the imported module into the project, using file -> add folder to workspace. In my case this was /Users/robinl/anaconda3/lib/python3.6/site-packages/great_expectations/
Within VS code, you can then navigate to the file you want to debug and set a breakpoint by clicking to the left of the code as normal.
I have a homework assignment in which i have to edit a very large project (add code in certain places). The thing is that the project has an import __main__ statement which PyCharm underlines with a red curly line and says: "no mudule named __main__".
I don't quite understand how the project runs without crashing- when i debug that import line it is carried out and the debugger continues to the next line without crashing, probably recognizing the module and therefore is able to access its dictionary.
I've seen some posts stating it has to do with bug track in PyCharm. I tried resetting cache and it didn't help.
The project is in Python 2.7 and so is the configured interpreter.
The project works just fine from command line also.
Any ideas ?
Edit: I tried isolating the issue by opening an empty module, importing __main__ in it, declaring a global variable and then accessing that variable - it worked even though PyCharm reported it as error with red curly line under the import statement. I really can't understand how it works (?)
That's PyCharm not quite understanding the import system. __main__ is the name of the module Python creates for a program's top-level script, regardless of the name of the script's file.
PyCharm appears to be expecting a __main__.py file, but no such file is necessary. The code is fine.
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.