How to get out of interactive mode in Python - python

This obviously an extremely novice question, but I've installed Python 2.7 and started reading the manual. However I looked and looked, and couldn't understand how to start programming a file rather than writing in interactive mode. One book that was online suggested quit(), which surprise -- quit the program.
Should coding be done in a different program? I'm using IDLE (Python GUI). Can coding not be done within that program?

Yes, coding should be done in a different program. The interactive shell is very useful but it's not an editor.

You write Python code line by line (as you would on Python interactive mode) in a text editor such as vim, emacs etc...
Then you run these line by line code using the Python interpreter by giving it the name of your script.
$ python myscript.py

I like to use a different directory for each project. Suppose I decide to use W:/mytest as my directory. First I create the directory.
Then I start Idle. I type the following:
import os
os.chdir("W:/mytest")
This makes W:/mytest the current directory for Idle.
import sys
sys.path.append(".")
This changes the path so that when I "import", it will look in the current directory.
Next I do File / New Window to open an editor window, and in that new window I select File / Save As. It starts in the Python home directory so I have to navigate to W:/mytest. I save this (empty) file as "test1.py".
I type this into my test1.py file and save it again:
""" test1.py is my test
"""
print ("This is test1.")
class Test1:
def __init__(self):
print ("Constructed")
This is a contrived example that can be run as a script or imported as a module.
So I have two windows now; an editor window and the Idle "Python Shell". I can do this in the Python Shell:
>>> execfile("test1.py")
This is test1.
>>> import test1
This is test1
>>> tt = test1.Test1()
Constructed

Push new to start making your own script file. Then when you are ready to test click run and then you can watch the results in the interactive mode, and even try new things as if you were adding code to the end of your script file, its a very useful app for debugging, testing and trying new things.
Also in the options you can change the way python opens your scripts when you click edit from windows, you can set it so that it opens the interactive shell or just the editor.

use new window tool in the file icon,in the python idle itself to write a program

To start coding in a file, just open a new file and start typing.

Related

Beginner question about finding Python script in IDLE shell

I'm a beginner in Python with no prior programming experience, so bear with me here.
I installed Python, started playing with it (typing variables, playing with math operations) in the Shell window and everything is fine. I open a New Window and started writing a simple script. Something like this:
print (1+1)
I press Run Module, and I am asked to name and save the script first. I do so by calling it firstscript.py, and save it to my desktop.
Now I press Run Module, and in the shell window 2 is printed on the screen. Everything is fine. I close Python, and open it up again. Now in the shell window, I type firstscript.py and I get the red message NameError: name 'firstscript' is not defined.
I can run my program only if I open the script file on my desktop and press Run Module from there, but if I try to start it up directly in IDLE Shell by typing its name, I get the error message.
What did I do wrong? Thank you.
Good to see that you are starting with python.
Firstly, you can run the file directly using 'Run Module' only when you have the file open. Once you save the file and quit, you are out of the file editor and back to the terminal.
Simply typing in firstscripty.py will not work as it does not recognize the command.
To run the file from the terminal, use the below code:
python [locationOfFile\]firstscript.py
You can check out this detailed explanation: https://realpython.com/python-idle/#how-to-work-with-python-files
The problem here is the Shell doesnt know that your firstscript.py is sitting on the desktop
The simplest way i suggest using cmd with:
python C:\Users\{your user}\Desktop\firstscript.py

How can I run a .py file with its options in Python console?

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.

How to execute Python file

I am learning Python and DJango and I am relatively nub with Linux. When I create DJango project I have manage.py file which I can execute like ./manage.py runserver. However when I create some Python program by hand it looks like that my Linux trying to execute it using Bash, not Python. So i need to write python foo.py instead ./foo.py. Attributes of both files manage.py and foo.py are the same (-rwx--x---). So my Q is: where is difference and how I can execute python program without specifying python? Links to any documentations are very appreciate. Thanks.
You missed one step, after give the corrects permissions to the file, open your foo.py then put this on the first line
#!/usr/bin/env python
Then you can use ./foo.py
I am just gonna add this for more clarity and to anyone coming across this post who might need an explanation.
Why do people write #!/usr/bin/env python on the first line of a Python script?
explains why you should it is used.
Save your python code file somewhere, using "Save" or "Save as" in your editor. Lets call it 'first.py' in some folder, like "pyscripts" that you make on your Desktop. Open a prompt (a Windows 'cmd' shell that is a text interface into the computer): start > run > "cmd".

how to output all the lines into python console in vim?

I have set F2 prompt key with map <f2> :w<cr>:! D:\Python34\python %<cr>,when i open an python file in vim and press F2,the python file will be executed .For a simple example,
here is my python file and opened in gvim .
Now i can't input other python lines ,only thing i can do is to see the result and hit any key to close this window.
What i want is :
when i press F2, (the python file was opened in gvim) ,the python console pop up,and all the files in the python file were copied into the python console automatically,and i can go no to input some lines such as Obj().hello in the python console or go on to edit in gvim ,i am a lazy man ,the gvim and python console all opened waiting to serve me , can i write a vim scripts to achieve the target?
The command :!D:\Python34\python -i % works fine ,i got the ouput
There is still a problem remain,
1)when command :!D:\Python34\python -i % works ,the gvim window will be frozen , i can't drag my mouse to see codes in vim.
2)there is no any python codes in the python console wiondow
So if the program is full of many lines ,and i can't remember the previous content ,worse still, the gvim window frozen ,how can i get the codes?
Avoid blocking
To make the call asynchonous (to avoid that GVIM is blocked during the Python session), use the Windows-specific :!start command:
nnoremap <f2> :w<cr>:!start D:\Python34\python -i %<cr>
List teh codez
I don't know whether it is possible to list the passed source code from the interactive Python debugger. But you can print the file contents before starting it:
nnoremap <f2> :w<cr>:!start cmd /c type % && D:\Python34\python -i %<cr>
Additional tips
You should use :noremap; it makes the mapping immune to remapping and recursion.
As your mapping only works correctly from normal mode, use :nnoremap (or extend it to support visual-mode selections, too).
Maybe Vim plugin Conque will solve your problem:
Installation instrucions are here https://code.google.com/p/conque/
To use just type :ConqueTermVSplit python -i test.py (VSplit is for vertical split - you may use horizontal)
There is no blocking of your window with python code - you may escape interactive mode and switch to your window with Ctrl+W twice
You could approach the problem from the Python angle (2.7).
Keep the file where it is (or save it with some unique name to a temporary directory) and have python load the file directly.
Go to that location in your shell and run python interactively (or have vim spin off an interpreter for you)
Import your file import demo
Experiment with what you have implemented demo.SomeModule().meth()
Make some changes in vim
Reload your python module reload(demo)
Experiment with your code again demo.SomeModule().differentMeth()
You can also have vim create a file with shortcut functions for loading/reloading the file you are working on. When vim kicks off the interpreter, you can have it set this file to the PYTHONSTARTUP environment variable, which is a file the interpreter will automatically load when it starts up. For example, you could have a function called r() to automatically reload the file you are working on.
It's also worth mentioning that reloading modules can be a little weird. If you instantiate some modules then reload the file, only new modules will use the new code; the old modules will run with the old code.

Opening a file, and taking input from the file opened in a Python program

I have written a program in python that is another front end for un-tarring files on OSX. I want to be able to double click on the file and open with the program that I wrote. How do I make the program automatically know that it is being opened with that file, and to work on that file?
You will need to make your make your script executable with the command chmod a+x <your script.py>
You will also need to tell your OS that the python interpreter is needed to execute this file. In Linux the line #!/usr/bin/env python at the top of the file is what does this. I assume its the same in OSX.
Then right click and select "Open with" and then "Other...". And select your script.
The Python script will need to be configured correctly to run when the OS calls it in this way.
Another way to do it(Caveat: I haven't personally tried this) is to use a shell script as advised in this anwer on the superuser forums.
Python scripts on OS X are not by default recognized as launchable applications by the Finder. What you need to do is use a tool that will package your Python script as a Mac OS X application. Then, you can right-click or ctrl-click a file of your chosen file type and locate that application through the Open With... dialog.
One option I'm aware of for doing this is part of the MacPython package, called py2app:
http://wiki.python.org/moin/MacPython/py2app
So, your steps would be:
1) Use py2app to package your Python script as a launchable application
2) Associate the application with the file type you'd like it to open using by right-clicking or ctrl-clicking one of that file type and choosing "Open With..." in the OS X Finder.
import sys
print("Program.py executing...")
for x in sys.argv:
print(x)
Produces the output
Program.py executing...
Program.py
something.tar
I'm windows, running this command:
python Program.py something.tar
I don't think anything changes from that command to OSX.
And as said by benjamin, the OS is responsible for determining what program is used for the file. I don't know what the command line from your os will be, but you can find out with the above program.

Categories

Resources