IDLE autocomplete in a new file do not work - python

If I testing my codes on IDLE the autocomplete its works but if I open a new file don't.
See there pictures below:
I just press CTRL + SPACE.
So.. don't work in this case:
I'll think there are some configuration for solve this, any one knows?

Python idle doesn't work that way. You get autocomplete in idle shell because values are deduced in every run. When you use files your program is not evaluated until you run. Because you can assign any type to a variable at run time, there is no way for idle to confirm the type of variable.
Understand with an example
>> a = dict()
>> a = set()
>> a. # <-- autocomplete knows type of a is set
but the same code in a file
a = dict()
a = set()
a. # <-- How does idle come to know what this variable is without running
but when you run this file once your global variables will show autocomplete feature, but not the local scope variables.

Have you tried saving the script as a *.py file before trying to use IDLE's autocomplete?
More than that, have you considered using a text editor with Python plugins, like Sublime Text and Atom? Or even a python-compatible IDE, like PyCharm, Spyder or even JupyterNotebook.

Related

How can you open a saved .py file in idle3 without it defaulting to normal text?

I recently started using idle3 to follow along with some course material as recommended by the instructor. Opening a new shell and running python code works just fine, the problem is when i save the file and later try to reopen it to continue on with the course work.
When ever i open the designated .py file, it only loads up in regular text, i can no longer execute new code, the line break doesn't have the ">>>" before each line, it won't even give any output
How can i open a saved file and continue on implementing code?
The basic use of the IDLE is for 2 thing, text editor and interactive console.
The interactive console allow you to write any python code and see it running immediately, great quick calculation and/or testing code until you get the desired result.
The save option (File -> Save) is deceptive however, because it save everything as you see including the >>> so saving as .py just doesn't work, or not without some extra work, namely removing all the >>> and all other undesired stuff, so is more like screenshot of sort.
The text editor mode is, well, just that but specialized for python with its syntax highlight and whatnot, use it to write your modules or whatever else, save it as .py and run the code by pressing F5 in order to test it, which will open a new interactive console with all that code loaded into it or would load it into a previously open one in which case it will reset it first, and that means that anything not in the file will be discarded (but you can scroll up can copy-pasted again if needed)
So for example, in a file you have
def greetings(name):
print("hello",name)
and you open it with the text editor mode of IDLE, simply run (F5) and you now have access to that function in the interactive console
>>> greetings("bob")
hello bob
>>> a=23
>>>
and lets make a new variable with some value
Now lets said we go back to the file and add some more stuff and now it looks like
def greetings(name):
print("hello",name)
def add(a,b):
return a+b
b=42
and run it again, this reset the console, which is indicated a msj like this containing the path of the loaded file
====== RESTART: C:\Users\Copperfield\Documents\StackOverflow\example.py =====
>>>
now we have the greetings and add function but the variable a from before is now loss
>>> a
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
a
NameError: name 'a' is not defined
>>>
but you have b
>>> b
42
>>>
So, use the text editor mode to write all the stuff you want to keep and in the interactive console play with it to test that is indeed the thing you want, and if not just go and edit it some more...

How to run python from C# without .exe file

I am a Python beginner and wrote some Python code that I want to run from my C# code.
In all the answers I have seen already, the way was to make a .exe file from the .py one and run it by system call.
However, I want it so that I do not need to make the .exe file and can write the commands with arguments as I could in the command line.
C:\Users\ntuser> python C:\Users\ntuser\Documents\run_python.py 3
Is there a way to do it?
I found a way to pass just one command—but I need to make two: 1. Go to "C:\Users\ntuser" 2. Run the Python code.
Thanks!
OK, so I found a solution.
Thanks to UnholySheep for the help.
What you need to do is:
Make the python as system variable
Go by code to your home directory:
Directory.SetCurrentDirectory(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile));
Add this code for calling the python code:
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;//if you want to hide the window
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C python pytonPath\\python_code.py";
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();//if you want to wait

Prevent "runfile(...)" expression in Spyder console

I'm just getting started with Python and trying to get some easy code-examples to compile. I am using the 'Spyder' Editor and everytime I run code it shows 'runfile(...)' before the actual compiled code in the console.
Is there a way to prevent this behaviour?
Try including this instead immediately prior to your code. The terminal will now return a clean code only response:
cls = lambda: print("\033[2J\033[;H", end='')
cls()
you are trying to run the code, instead go to settings, keyboard shortcuts, and look for "run selection" it will have a shortcut assigned to it
Now select all the code and use the shortcut
it will only give you in and out

Enthought Canopy python - name ' ' not defined

I'm very new to using canopy and programming in general.
I'm trying to define a function in Python in the canopy editor. This used to work for me but has suddenly stopped and I have no idea why.
As a basic example, in the editor I wrote;
def funct(x):
return x
When write funct(1) in the shell I get the error message
NameError: name 'funct' is not defined
Any ideas?
Thanks
You need to "run" your script (in the editor) before its results actually exist (and are visible in) the Python shell. In this case the results of your script are to define your function. Just writing the function in the editor doesn't actually create it in Python until you run the script.
As Ali correctly said, another (deeper) approach is to import the script (in this case known as a module), but I think running is probably more what you have in mind.
I've never used Canopy before, but in general you would save the file where your function is defined somewhere in your working directory (e.g. as myfunct.py), then import it into the shell namespace:
In [1]: import myfunct
In [2]: myfunct.funct(1)
Out [2]: 1

Detect where Python code is running (e.g., in Spyder interpreter vs. IDLE vs. cmd)

Is there a way in Python to detect, within a process, where that process is being executed? I have some code that includes the getpass.getpass() function, which is broken in Spyder, and it's annoying to go back and forth between the command line and the IDE all the time. It would be useful if I could add code like:
if not being run from Spyder:
use getpass
else:
use alternative
Here is the solution I ended up using. After reading Markus's answer, I noticed that Spyder adds half a dozen or so environment variables to os.environ with names like SPYDER_ENCODING, SPYDER_SHELL_ID, etc. Detecting the presence of any of these seems relatively unambiguous, compared to detecting the absence of a variable with as generic a name as 'PYTHONSTARTUP'. The code is simple, and works independently of Spyder's startup script (as far as I can tell):
if any('SPYDER' in name for name in os.environ)
# use alternative
else:
# use getpass
Since the string is at the beginning of each environment variable name, you could also use str.startswith, but it's less flexible, and a little bit slower (I was curious):
>>> import timeit
>>> s = timeit.Timer("[name.startswith('SPYDER') for name in os.environ]", "import os")
>>> i = timeit.Timer("['SPYDER' in name for name in os.environ]", "import os")
>>> s.timeit()
16.18333065883474
>>> i.timeit()
6.156869294143846
The sys.executable method may or may not be useful depending on your installation. I have a couple WinPython installations and a separate Python 2.7 installation, so I was able to check the condition sys.executable.find('WinPy') == -1 to detect a folder name in the path of the executable Spyder uses. Since the warning that shows in IDLE when you try to use getpass is less "loud" than it could be, in my opinion, I ended up also checking the condition sys.executable.find('pythonw.exe') == -1 to make it slightly louder. Using sys.executable only, that method looks like:
if sys.executable.find('pythonw.exe') == sys.executable.find('WinPy') == -1:
# use getpass
else:
# use alternative
But since I want this to work on other machines, and it's much more likely that another user would modify their WinPython installation folder name than that they would rename their IDLE executable, my final code uses sys.executable to detect IDLE and os.environ to detect Spyder, providing a "louder" warning in either case and keeping the code from breaking in the latter.
if any('SPYDER' in name for name in os.environ) \
or 'pythonw.exe' in sys.executable:
password = raw_input('WARNING: PASSWORD WILL BE SHOWN ON SCREEN\n\n' * 3
+ 'Please enter your password: ')
else:
password = getpass.getpass("Please enter your password: ")
By default, Spyder uses a startup scrip, see Preferences -> Console -> Adanced setting. This option is usually set to the scientific_startup.py file that loads pylab et al.
The easiest solution is to just add a global variable to the file and then use that in your if statement, e.g. add this line at the end of scientific_startup.py:
SPYDER_IDE_ACTIVE = True
In your script:
if not 'SPYDER_IDE_ACTIVE' in globals():
use getpass
else:
use alternative
This will work without throwing an error. You can also use exceptions if you like that more.
A second solution would be (if you cannot modify that file for some reason) to just check if the environment variable PYTHONSTARTUP is set. On my machine (using the Anaconda Python stack), it is not set for a regular Python shell. You could do
import os
if not 'PYTHONSTARTUP' in os.environ:
use getpass
else:
use alternative
Spyder provides the option of executing the current editor script in a native system terminal. This would produce identical behavior as if you were running from the command line. To set this up, open the Run Settings dialog by hitting F6. Then select the radio button "Execute in an external System terminal". Now run the script as usual by hitting F5. You should be able to use getpass in the normal fashion with this approach.
You could add env variable when running in Spyder and check it in code.

Categories

Resources