I'm using canopy python. The shell has commands "pwd" and "cd".
It even does autocomplete.
Is there a command - not something I have to write and keep track of - a built-in command that just lists the files in the directory.
I've tried ls, ls(), dir, dir(), directory, directory(), files, files(), filelist, filelist().
I've searched their documentation for listing files. It shows how to get a list of files in a python program - that's great. I do that all the time. I don't want to do that every time I want to list the contents of the current directory.
Is there a built-in shell command for this?
You can try
import os
fileList = os.listdir(directory_path)
so that you have the list of files in the python program to manipulate.
If you want the list of files in the current working directory in the way that ls would give you you can do.
fileList = os.listdir(os.getcwd())
If you really want a short command to type over and over you can write
ls = lambda : os.listdir(os.getcwd())
and then it will run this command when you type
ls()
You can use the python built in module, os, to query a directory using the system method. Please see below.
import os
os.system("dir")
Update
Please keep in mind that my solution is OS specific (i.e. ls vs dir) so Jon's solution is preferable.
The premise of the question seems inconsistent. If you can do the ipython pwd or cd standard magic commands, then you should also be able to access the ipython standard alias ls. If you cannot, then it almost certainly because you've overwritten / shadowed the meaning of the ls alias.
It's crucial to distinguish between (1) a plain Python shell (opened by typing python at a Canopy command prompt), which does not provide pwd nor cd nor 'lscommands; and (2) *any* IPython shell, whether the Python panel in the Canopy GUI or anipython` terminal in the Canopy Command Prompt, which does provide those, and many other Ipython "magic" commands.
(For more about IPython magic commands, see http://ipython.readthedocs.io/en/stable/interactive/magics.html; these are the docs for IPython version 6, but they are mostly the same for IPython version 5 which Canopy uses in order to support both Python 2.7 and Python 3.5+.)
The two previous answers are always correct in that they will work in any Python program or shell (depending on OS). That is because they only use the Python standard library. However they are not analogous to the cd and pwd commands that you mention, which are specific to the IPython shell (not to programs running in an IPython shell).
IMO, there is very seldom a good reason for opening a plain Python shell. If you simply want to run a script file from a Command Prompt, then by all means python myscript.py. But if you want an interactive shell, IPython provides so much extra capability that it has been for many years the de facto standard for Python shells (which is why it is used for the Canopy GUI's Python shell).
Got a note back from Canopy Support).
There is an environment variable, COMSPEC that was set to:
C:\windows\system32\cmd.exe;
That semicolon at the end is wrong. This is a single directory and not a list of directories. I removed that semicolon and suddenly the 'ls' command works as I remember!
Related
My use case is I want to initialize some functions in a file and then start up IPython with those functions defined. Is there a way to do something like this?
ipython --run_script=myscript.py
In recent versions of IPython, you do need to add the -i option to get into the interactive environment afterwards. Without the -i it just runs the code in myfile.py and returns to the prompt.
ipython -i myfile.py
Per the docs, it's trivial:
You start IPython with the command:
$ ipython [options] files
If invoked with no options, it
executes all the files listed in
sequence and drops you into the
interpreter while still acknowledging
any options you may have set in your
ipythonrc file. This behavior is
different from standard Python, which
when called as python -i will only
execute one file and ignore your
configuration setup.
So, just use ipython myfile.py... and there you are!-)
You can use IPython profiles to define startup scripts that will run every time you start IPython. A full description of profiles, is given here. You can create multiple profiles with different startup files.
Assuming you only need one profile, and always want the same startup files every time you start IPython, you can simply modify the default profile. To do this, first find out where your IPython configuration directory is in an ipython session.:
In [1]: import IPython
In [2]: IPython.paths.get_ipython_dir() # As of IPython v4.0
In [3]: print(ipython_config_dir)
/home/johndoe/.config/ipython
For this example, I am using Ubuntu Linux, and the configuration directory is in /home/johndoe/.config/ipython, where johndoe is the username.
The default_profile is in the profile_default subdirectory. Put any starting scripts in profile_default/startup. In the example here, the full path would be /home/johndoe/.config/ipython/profile_default/startup.
Nowadays, you can use the startup folder of IPython, which is located in your home directory (C:\users\[username]\.ipython on Windows). Go into the default profile and you'll see a startup folder with a README file. Just put any Python scripts in there, or if you want IPython commands, put them in a file with an .ipy extension.
You seem to be looking for IPython's %run magic command.
By typing in IPython:
%run hello_world.py
you'll run the hello.py program saved in your home directory. The functions and variables defined in that script will be accessible to you too.
The following is for the case when you want your startup scripts to automatically be run whenever you use IPython (instead of having a script that you must specify each time you run IPython).
For recent versions (i.e., 5.1.0) of IPython, place one or more python scripts you wish to have executed in the IPYTHON_CONFIG_DIR/profile_PROFILENAME/startup folder.
On Linux, for example, you could put your Python startup code into a file named ~/.ipython/profile_default/startup/10-mystartupstuff.py if you want it to run when no IPython profile is specified.
Information on creating and using IPython profiles is available here.
Update to Caleb's answer for Python 3.5 in UbuntuĀ 14.04 (Trusty Tahr): I made this answer self-contained by copying relevant parts of Caleb's answer.
You can use IPython profiles to define startup scripts that will run every time you start IPython. A full description of profiles, is given here. You can create multiple profiles with different startup files.
Assuming you only need one profile, and always want the same startup files every time you start IPython, you can simply modify the default profile. To do this, first find out where your IPython configuration directory is in an IPython session:
Input:
import IPython
ipython_config_dir = IPython.paths.get_ipython_dir()
print(ipython_cofig_dir)
Output:
/home/johndoe/.ipython
For this example, johndoe is the username.
Inside the /.ipython folder, the default_profile is in the profile_default subdirectory. Put any starting scripts in profile_default/startup. In the example here, the full path would be
/home/johndoe/.ipython/profile_default/startup
I would like to use a python script anywhere within command prompt. This is possible in unix, but I couldn't find anything for windows. Do I have to convert it to .exe?
Edit: not sure why this is being downvoted, maybe it's a silly question but I can't find any similar threads here and I can't be the first person to want to execute .py scripts from their path...
Edit 2: I think my wording was unclear. I would like to know a method to execute python scripts in Windows without needing to specify python path/to/script.py every time. Here is a solution on Linux where the shebang statement invokes the python interpreter, and the script in question can be easily placed in bin: How do I install a script to run anywhere from the command line? . Does there exist a solution like this for Windows?
Here's a solution for running myScript.py:
add to the myScript.py file a first line #!python (or #!python3 if you want to use Python 3)
For instance:
#!python
import sys
sys.stdout.write("hello from Python %s\n" % (sys.version,))
change the "opens with" property of myScript.py to py.exe (to find where it is use where py-- I have it in C:\Windows\py.exe)
put the script myScript.py somewhere in your Windows path
and now you should be able to type myScript.py anywhere in a command prompt and run the Python script with your chosen Python version.
See: https://docs.python.org/3.6/using/windows.html#from-the-command-line
I'm trying to use gud-pdb for Python debugging within Emacs.
Having an issue that pdb doesn't seem to be searching the PATH when looking for my .py files
I.e., I have a python script in a dir which is on the PATH, I can run this script from anywhere outside of pdb, i.e., from the command line.
But when I try and run it from within pdb it tells me the file doesn't exist.
I'm trying to run pdb against the script in a dir that contains the data to be processed.
I think this is a standard thing to want to do. I successfully do it for gdb and C programs all the time.
Anyone had this issue and know how to fix it?
Given that you're able to run your script outside of Emacs, but not
within, you probably
need
exec-path-from-shell.
This syncs up environment variables (like PATH) between your shell
and Emacs.
Have you tried the realgud package since you are using python?
;;M-x load-library realgud python -m pdb myscript.py
(package-install 'realgud) ;; python debugging in emacs
(defun sdev/init-realgud
(interactive)
(load-library "realgud"))
(sdev/init-realgud 1)
I am using several applications that are using different versions of Python:
Nuke - 2.7
3Dequalizer - 2.6
linux - 2.6.6
I am getting various problems trying to get them all to communicate with one another, so I was wondering if it's possible to change Python interpreter during a script.
E.g. Start in 2.6, then run a Python script in 2.7 from a script in 2.6
EDIT:
nuke_install = "/path/to/nuke"
cmd = nukeLauncher + " -t"
os.system(cmd)
The -t flag allows for nuke to be run without a GUI. This code works when run in a Python interpreter, but when I run via a Python script in 3dequalizer it gives me the:
ImportError: No module named site
To add another level of confusion, I can import site inside 3dequalizer. The sys.path for 3dequalizer contains the same paths as when run directly from the interpreter, with a few additions for the python lib that comes with 3de.
Also PYTHONPATH is empty inside 3dequalizer. Does this matter if sys.path is pointing to the right paths?
I am not sure it is really the way to go; but if you really want to do it, you could use the os.system command with somthing like:
os.system("python2.7 myscript.py")
which will execute the program python2.7 (as long as it is in your executable path) with the name of the script as its argument (before returning to the current) statement in your initial script.
But honestly, I think you should do it in some other way. Regards.
Okay, I'm having one of those moments that makes me question my ability to use a computer. This is not the sort of question I imagined asking as my first SO post, but here goes.
Started on Zed's new "Learn Python the Hard Way" since I've been looking to get back into programming after a 10 year hiatus and python was always what I wanted. This book has really spoken to me. That being said, I'm having a serious issue with pydoc from the command. I've got all the directories in c:/python26 in my system path and I can execute pydoc from the command line just fine regardless of pwd - but it accepts no arguments. Doesn't matter what I type, I just get the standard pydoc output telling me the acceptable arguments.
Any ideas? For what it's worth, I installed ActivePython as per Zed's suggestion.
C:\Users\Chevee>pydoc file
pydoc - the Python documentation tool
pydoc.py <name> ...
Show text documentation on something. <name> may be the name of a
Python keyword, topic, function, module, or package, or a dotted
reference to a class or function within a module or module in a
package. If <name> contains a '\', it is used as the path to a
Python source file to document. If name is 'keywords', 'topics',
or 'modules', a listing of these things is displayed.
pydoc.py -k <keyword>
Search for a keyword in the synopsis lines of all available modules.
pydoc.py -p <port>
Start an HTTP server on the given port on the local machine.
pydoc.py -g
Pop up a graphical interface for finding and serving documentation.
pydoc.py -w <name> ...
Write out the HTML documentation for a module to a file in the current
directory. If <name> contains a '\', it is treated as a filename; if
it names a directory, documentation is written for all the contents.
C:\Users\Chevee>
EDIT: New information, pydoc works just fine in PowerShell. As a linux user, I have no idea why I'm trying to use cmd anyways--but I'd still love to figure out what's up with pydoc and cmd.
EDIT 2: More new information. In cmd...
c:\>python c:/python26/lib/pydoc.py file
...works just fine. Everything works just fine with just pydoc in PowerShell without me worrying about pwd, or extensions or paths.
In Windows Powershell use: python -m pydoc
Examples:
python -m pydoc open
python -m pydoc raw_input
python -m pydoc argv
When you type the name of a file at the windows command prompt, cmd can check the windows registry for the default file association, and use that program to open it. So if the Inkscape installer associated .py files with its own version of python, cmd might preferentially run that and ignore the PATH entirely. See this question.
Based on your second edit, you may have more than one copy of pydoc.py in your path, with the 'wrong' one first such that when it starts up it doesn't have the correct environment in which to execute.
python -m pydoc -k/p/g/w <name>
Syntax for pydoc on windows:
alt1:
C:\path\PythonXX\python.exe C:\path\PythonXX\Lib\pydoc.py -k/p/g/w X:\path\file_to_doc.py
alt2:
python -m pydoc -k/p/g/w X:\path\file_to_doc.py
Of which the latter is the one to prefer, duh. However it requires your windows installation to have registered python to the environment variable "Path".
Setup windows environment variables:
Look at this site for a guide on where to find them. The one you'll be looking for is "Path". If you select Path and click Edit you will see a long row of paths pointing to different folders. The Path's you see here is what allows you to basically reach a veriety of programs in the command line by just entering the name of the program, instead of the whole path to it. So what you want to do here is to locate your Python installation and copy its full path like this: X:\subfolders\PythonXX\ Then you add it to the very end of the long row of Path's like this:
X:\earlier\path\to\something;X:\subfolders\PythonXX\
Notice the ";" that seperates the different paths, make sure not to forget it. When done, click to confirm/Ok, then you would need to restart any cmd.exe that's already open.
The pydoc.py
The thing is that pydoc is a module of the standard python lib, and it's also powered by python. The windows environment, of what I understand, requires you to specify with which program you want to run a certain file with. So to run the pydoc.py-file we would use:
Open file in windows cmd.exe:
X:\subfolders\Python27\python.exe X:\subfolders\Python27\Lib\pydoc.py
pydoc.py's arguments:
pydoc.py comes with a veriety of command line-based features that allows you to enter certain arguments:
-k/p/g/w of which will trigger different behaviours of the pydoc.py-program.
Send arguments to a program through command line:
The syntax to enter these arguments is of what I know always after the x:\pathtofile\filename.suffix, seperated by a simple space. Which gives us the final:
alt1:
X:\subfolders\Python27\python.exe X:\subfolders\Python27\Lib\pydoc.py -w X:\path\file_to_doc.py
alt2 (with python registered to path):
python -m pydoc -w X:\path\file_to_doc.py
The "w"-option will give you a HTML-documentation for the file you want to run documentation on. Notice that pydoc.py will (according to my tests) create the documentation-file in the current working directory. Meaning that you will need to place yourself in a folder of choice before you actually run the command.
The function of -m
Of what I can find, the -m seem to handle registry entries, atleast in the msiexec.exe. I guess it might be used for programs in general this way. So my speculative idea of it is that if "-m" is applied, the pursuing arguments paths will be rewritten so that the .exe-file will be used as a path-reference. But as said, rather speculative.
-m Rewrites all required computer-specific registry entries. (in msiexec.exe) According to Microsoft