Python: import standby script

This has probably been asked before, and is indeed basic, but:

I am using Windows 7. I have Idle for Python 2.4.4 and 3.1. I have some scripts that are in different places on my file system. I would like to import them and play with my types. How can i do this?

On Ubuntu, the command import scriptname works if the directory I called python from contains the scriptname . How do I import a script from another place?

+8
python
source share
2 answers

In standby mode, you can add the path containing the scriptname.py file.

 >>> import pprint >>> import sys >>> print pprint.pprint(sys.path) # you could just move your scriptname.py to a directory in the sys.path list >>> sys.path.append(r"C:\Users\You\") >>> import scriptname 

You can also set the PYTHONPATH environment variable on Windows to include other directories, such as "C: \ Users \ You \ lib"

+6
source share

To import a script from IDLE you can do:

 >>> import os >>> os.chdir('C:\\Users\\You\\Some\\Arbitrary\\Path') >>> import scriptname 

Keep in mind that you will need to call constructors with a scriptname. prepended e.g. scriptname.myClass(...)

If you changed something in the script, you need to reload it as follows:

 >>> import imp >>> imp.reload(scriptname) 

(There is an easier way if you just want to play with types from a single script, and if the script contains only definitions of functions and classes (without running code). Then you can simply open the script in IDLE and go to Run>Run Module . When you use this method, there is no need to put scriptname. before the constructors.)

+1
source share

All Articles