Python is very first programming language i'm learning , i'm following "python programming by John Zelle". The problem is that after creating module Chaos i'm not able to import this module, it shows error message that " Import error: No module name chaos.
I can see the confusion. I have actually read this book as well when I was learning. First be sure you launch python in the same directory as Chaos.py and be sure to use a capital C if that is how you named it.
To import it in the python interpreter you would not type import Chaos.py just import Chaos and then call the main function as follows:
import Chaos
Chaos.main()
If you wanted to run the script in python you can just type the following from a command line in the same directory as the .py file:
python chaos.py
(These directions assume Python 3 on Windows. If your system is different then please edit the question to tell your system and version.) First create a file named chaos.py on your desktop. In the file, paste the following:
# File: chaos.py
def main():
print("This program illustrates a chaotic function")
x = float(input("Enter a number between 0 and 1:"))
for i in range(10):
x = 3.9*x*(1-x)
print(x)
if __name__ == "__main__":
main()
Next, to make this as easy as possible, we will use a modified IDLE shortcut:
Copy your current IDLE shortcut and paste it to your desktop to create a new shortcut.
Right-click on the new shortcut and click Properties.
Change the Start In box to %USERPROFILE%\Desktop. Click OK.
Now open IDLE by clicking on the new shortcut. Then enter:
import chaos
chaos.main()
There's an easy solution, the way I got it to work was instead of making the module perform inside a IDLE environment, I opened up sublime text(a program similar to notepad++), and I essentially wrote the code inside of there and saved it as a python file called "Chaos.py" inside of the folder where IDLE runs, which is :
(C:\Users\ngltm\AppData\Local\Programs\Python\Python36-32\) )
, the name next after the "Users" will be different for you, but I saved it inside of the Python36-32 file and after saving it inside of sublime text, I opened up a IDLE program and wrote "import Chaos" and it worked! The problem was the text in the beginning of every IDLE file that starts off with :
"Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information."
Well, I hope this helped!
Related
I'm using Anaconda Python 3.6.1 on Windows 10.
My program takes weather data from an Atom feed and writes it to a .csv file every 30 minutes (or 2 seconds for testing purposes). When I run the program from PyCharm, it writes the data no problem. However, when I try to run the program from the command line the .csv file is completely unchanged. I added a print statement after the writing and it prints to the terminal every 2 seconds no problem, it just doesn't write the data.
I call it through command line this way:
python e:\documents\pythonprojects\weatherfeed\weatherfeed.py
and my functions that write data are as follows:
def write_current_temp():
""" Writes current temperature to weather_data.csv on same line """
with open('weather_data.csv', 'a') as wd:
wd.write(get_current_temp() + ',')
def new_day():
""" Creates a new line, adds yy.mm.dd to line, adds current temp """
with open("weather_data.csv", 'a') as wd:
wd.write("\n")
wd.write(time.strftime("%y.%m.%d,"))
wd.write(get_current_temp() + ',')
where get_current_temp() gets the current temperature from the feed and returns it as a string
weather_data.csv is in the same folder as my .py file and it works 100% perfectly when I run it from PyCharm
Any ideas what the problem could be?
Thanks!
Edit: Using Python 3.6.1 on PyCharm, I'm pretty sure that's the only version I've ever installed on this machine. The command line appears to be running 3.6.1: I don't have it installed on my path so I run from e:\applications\anaconda and checking the version that way on the command line yields this:
e:\Applications\Anaconda>python
Python 3.6.1 |Anaconda 4.4.0 (64-bit)| (default, May 11 2017, 13:25:24) [MSC v.1900 64 bit (AMD64)] on win32
You are specifying a relative location for the file, which will be relative to the directory from which you run the script, not the directory where the script lives.
You can try something like this to force it to look at the same directory as the script:
import os
this_dir = os.path.dirname(os.path.realpath(__file__))
file_path = os.path.join(this_dir, 'weather_data.csv')
with open(file_path, 'a') as wd:
wd.write(get_current_temp() + ',')
Hmmm, I am not sure if this is your case, but please check which python version Pycharm is running and which version your terminal is running. One of them could be running the python3.5 and the other 2.7, this could cause some issues. But again, I am not sure if this is your case, please update your question with the versions of pythons that you're running.
I am on Windows 7. When I launch Python IDLE, I want it to pre-load: pandas, numpy and matplotlib without me having to type out the import statements. I import them very frequently.
I have waded through several posts:
This one has to do with iPython, not IDLE-specific
This one has to do with running a script in IDLE
This one talks about PYTHONSTARTUP for interactive sessions
From these posts, I have determined that there is a distinct difference between Windows command-prompt python interactive shell and IDLE's interactive shell.
For example, I created defaultimports.py and put it in this location:
C:\Python34\Lib\site-packages\jaradspythonstartup
That script contains the following:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
print('pd, np and plt imported')
Next, on my machine, I went to Start > Computer > right-clicked Properties > Advanced system settings > environment variables > clicked New... and added a new variable named PYTHONSTARTUP, then put my path C:\Python34\Lib\site-packages\jaradspythonstartup\defaultimports.py
However, this seems to only work in Windows Command prompt when I open command prompt and type python. I do see it loads my print statement.
When I launch IDLE, I don't see the message: pd, np, and plt imported print statement. While in IDLE, if I import os and os.environ['PYTHONSTARTUP'], I do see my environment variable defined but don't know if that's important to note or not.
Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:15:05) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import os
>>> os.environ['PYTHONSTARTUP']
'C:\\Python34\\Lib\\site-packages\\jaradspythonstartup\\defaultimports.py'
>>>
My Question
How can I pre-load modules in IDLE on startup?
python -m idlelib -h on a command line, where python runs recent 3.x, will display startup commands for IDLE; use idlelib.idle for 2.x. It says that
idle idlelib -s "runs $IDLESTARTUP or $PYTHONSTARTUP before anything else".
If that does not work, try python -m idlelib -s.
Currently, when you restart the shell, which happens when you run a file from the editor, ....STARTUP does not get re-run. I hope to fix that.
EDIT: How to start IDLE with arguments from the desktop instead of command line.
Make a properly labelled IDLE desktop icon. Go to Start Menu > Python x.y > IDLE... and copy to Desktop. Control-Left Mouse Button drag or (Win 7, at least) Right click, Send to > Desktop (create shortcut). If for Python before 3.4, right click icon, select Rename, and label with the version number. (We recently got complaint "I installed 3.5 and (pre-existing) desktop icon opens 2.7.).
Make icon open IDLE with arguments. Right-click icon, select properties, click end (you may or may not have to click box first). Cursor should be at end of line with ...pythonw.exe...idlew.py. Space and add arguments. I tried -c "print('hello')" to test. Add -s for ...STARTUP. Consider renaming to indicate addition, such as IDLE 3.5 64 bit STARTUP, in case you want another IDLE desktop icon.
I've been using Wing IDE for python programming and I am trying to switch to Eclipse, PyDev.
When I run my code in Wing IDE, after finishing the execution the console goes right back to the interactive shell and I can continue on testing, but I don't know how to do this in Eclipse.
I'm not sure if I am describing my problem properly so I'll use an example:
Let's say I had a simple source code that looked like this (e.g. test.py):
print("hello")
When I run this in Wing IDE by clicking that green arrow, the console would look like this after execution:
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)]
Type "help", "copyright", "credits" or "license" for more information.
[evaluate untitled-1.py]
hello
>>>>
And I can keep doing whatever on the shell and it would know my code (defined functions etc.).
But when I do the same thing in Eclipse, the console would simply look like this:
hello
and I have to click "Remove All Terminated Launches" button to go back to the shell.
Can this be done in Eclipse?
What you want to use is the interactive console in PyDev (not the regular output when you do a run).
To use it do: Ctrl+Alt+Enter.
Note that if you're in the middle of a debug session, you can also use the debug session console to interact with the program.
It can also be created from the UI in the console view as shown below:
[
From what I know, we can open multiple consoles of a particular type in Eclipse.
Whenever we run a script within PyDev, it opens a new console to which it prints the output from the script (including error output). However this is just a new console that is added to the list of already opened consoles. Hence you can switch back to a previously open console by using the Display Selected Console option within the console view ( refer here for a list of all the available console options).
What does this mean?
You can open a new Python interpretor console using the Open Console option within the Eclipse Console view. You can define your methods and play with the interpretor within that console. You now run a Python script that is open within the PyDev editor. A new console gets opened up where-in you see the output from the script (includes error output too). Now if you want to go back to the interactive console, you simply choose the Python Interepretor console that you opened previously from the Display Console option.
Personally, I like this design where-in the output from your script does not mingle and mess up with your experimental sojourns on the Python console. This in turn results in a crisp, clear and concise view of what is happening within the various python environments.
Hope this bit of information helps.
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.
I am wondering, is there a way to change the name of a script so that it is not called "python.exe" in the tasklist. The reason I am asking is that I am trying to make a batch file that run's a python script. I want the batch file to check to see if the script is already running. if the script is already running then the batch file will do nothing. Thanks
Maybe you can try this : http://code.google.com/p/procname/
This library does not work on Windows, and shouldn't be used in production code. Manipulation the argv array is a rather dirty hack.
Generally I'd not try to identify processes by scanning the process table. This is not really reliable, as process names aren't guaranteed to be unique. Instead I'd spawn a simple server on localhost inside the python script. If started, the script can then try to connect to the server, and quit, if the server is already running. This approach can later on also be expanded to support any kind of IPC.
You could use py2exe to convert the Python script to a .exe file which means you could then give it any name you like.
Alternatively you could use Python itself (rather than a .bat file) using the approaches given at Reading Command Line Arguments of Another Process (Win32 C code) to determine the name of the scripts being run by the 'python.exe' processes.
I'd simply create a lockfile in the local filesystem and exit if this exists already.
Copy python.exe to a file name of your choice.
C:\Python26>copy python.exe my_proc.exe
1 file(s) copied.
C:\Python26>my_proc.exe
Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
In the tasklist it is showing as my_proc.exe.
I've tried to make a symlink of python.exe (mklink in Windows 7). Unfortunately it is still showing as python.exe in the task list.