Module:core.magics.osm
Implementation of magic functions for interaction with the OS.
Note: this module is named ‘osm’ instead of ‘os’ to avoid a collision with thebuiltin.
1 Class
- classIPython.core.magics.osm.OSMagics(**kwargs:Any)
Bases:
MagicsMagics to interact with the underlying OS (shell-type functionality).
- __init__(shell=None,**kwargs)
Create a configurable given a config config.
- Parameters:
config (Config) – If this is empty, default values are used. If config is a
Configinstance, it will be used to configure theinstance.parent (Configurable instance,optional) – The parent Configurable instance of this object.
Notes
Subclasses of Configurable must call the
__init__()method ofConfigurablebefore doing anything else and usingsuper():classMyConfigurable(Configurable):def__init__(self,config=None):super(MyConfigurable,self).__init__(config=config)# Then any other code you need to finish initialization.
This ensures that instances will be configured properly.
- alias(parameter_s='')
Define an alias for a system command.
‘%alias alias_name cmd’ defines ‘alias_name’ as an alias for ‘cmd’
Then, typing ‘alias_name params’ will execute the system command ‘cmdparams’ (from your underlying operating system).
Aliases have lower precedence than magic functions and Python normalvariables, so if ‘foo’ is both a Python variable and an alias, thealias can not be executed until ‘del foo’ removes the Python variable.
You can use the %l specifier in an alias definition to represent thewhole line when the alias is called. For example:
In[2]:aliasbracketecho"Input in brackets: <%l>"In[3]:brackethelloworldInputinbrackets:<helloworld>
You can also define aliases with parameters using %s specifiers (oneper parameter):
In[1]:aliaspartsechofirst%ssecond%sIn[2]:%partsABfirstAsecondBIn[3]:%partsAIncorrectnumberofarguments:2expected.partsisanaliasto:'echo first%s second%s'
Note that %l and %s are mutually exclusive. You can only use one orthe other in your aliases.
Aliases expand Python variables just like system calls using ! or !!do: all expressions prefixed with ‘$’ get expanded. For details ofthe semantic rules, see PEP-215:https://peps.python.org/pep-0215/. This is the library used byIPython for variable expansion. If you want to access a true shellvariable, an extra $ is necessary to prevent its expansion byIPython:
In [6]: alias show echoIn [7]: PATH='A Python string'In [8]: show $PATHA Python stringIn [9]: show $$PATH/usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
You can use the alias facility to access all of $PATH. See the %rehashxfunction, which automatically creates aliases for the contents of your$PATH.
If called with no parameters, %alias prints the current alias tablefor your system. For posix systems, the default aliases are ‘cat’,‘cp’, ‘mv’, ‘rm’, ‘rmdir’, and ‘mkdir’, and other platform-specificaliases are added. For windows-based systems, the default aliases are‘copy’, ‘ddir’, ‘echo’, ‘ls’, ‘ldir’, ‘mkdir’, ‘ren’, and ‘rmdir’.
You can see the definition of alias by adding a question mark in theend:
In [1]: cat?Repr: <alias cat for 'cat'>
- bang(line='',cell=None)
Shell execute - run shell command and capture output (!! is short-hand).
%sx command
IPython will run the given command using commands.getoutput(), andreturn the result formatted as a list (split on ‘n’). Since theoutput is _returned_, it will be stored in ipython’s regular outputcache Out[N] and in the ‘_N’ automatic variables.
Notes:
1) If an input line begins with ‘!!’, then %sx is automaticallyinvoked. That is, while:
!ls
causes ipython to simply issue system(‘ls’), typing:
!!ls
is a shorthand equivalent to:
%sxls
2) %sx differs from %sc in that %sx automatically splits into a list,like ‘%sc -l’. The reason for this is to make it as easy as possibleto process line-oriented shell output via further python commands.%sc is meant to provide much finer control, but requires moretyping.
3) Just like %sc -l, this is a list with special attributes:
.l(or.list):valueaslist..n(or.nlstr):valueasnewline-separatedstring..s(or.spstr):valueaswhitespace-separatedstring.
This is very useful when trying to use such lists as arguments tosystem commands.
- bookmark(parameter_s='')
Manage IPython’s bookmark system.
%bookmark <name> - set bookmark to current dir%bookmark <name> <dir> - set bookmark to <dir>%bookmark -l - list all bookmarks%bookmark -d <name> - remove bookmark%bookmark -r - remove all bookmarks
You can later on access a bookmarked folder with:
%cd-b<name>
or simply ‘%cd <name>’ if there is no directory called <name> ANDthere is such a bookmark defined.
Your bookmarks persist through IPython sessions, but they areassociated with each profile.
- cd(parameter_s='')
Change the current working directory.
This command automatically maintains an internal list of directoriesyou visit during your IPython session, in the variable
_dh. Thecommand%dhistshows this history nicely formatted. You canalso docd-<tab>to see directory history conveniently.Usage:cd'dir': changes to directory ‘dir’.cd-: changes to the last visited directory.cd-<n>: changes to the n-th directory in the directory history.cd--foo: change to directory that matches ‘foo’ in historycd-b<bookmark_name>: jump to a bookmark set by %bookmarkHitting a tab key after
cd-ballows you to tab-completebookmark names.
Note
cd<bookmark_name>is enough if there is no directory<bookmark_name>, but a bookmark with the name exists.Options:
- -q
Be quiet. Do not print the working directory after thecd command is executed. By default IPython’s cdcommand does print this directory, since the defaultprompts do not display path information.
Note
Note that
!cddoesn’t work for this purpose because the shellwhere!commandruns is immediately discarded after executing‘command’.Examples
In[10]:cdparent/child/home/tsuser/parent/child
- cd_force_quiet
Force %cd magic to be quiet even if -q is not passed.
- dhist(parameter_s='')
Print your history of visited directories.
%dhist -> print full history%dhist n -> print last n entries only%dhist n1 n2 -> print entries between n1 and n2 (n2 not included)
This history is automatically maintained by the %cd command, andalways available as the global list variable _dh. You can use %cd -<n>to go to directory number <n>.
Note that most of time, you should view directory history by enteringcd -<TAB>.
- dirs(parameter_s='')
Return the current directory stack.
- env(parameter_s='')
Get, set, or list environment variables.
Usage:
%env:lists all environment variables/values
%envvar:get value for var
%envvarval:set value for var
%envvar=val:set value for var
%envvar=$val:set value for var, using python expansion if possible
- isexec(file)
Test for executable file on non POSIX system
- popd(parameter_s='')
Change to directory popped off the top of the stack.
- pushd(parameter_s='')
Place the current dir on stack and change directory.
- Usage:
%pushd [‘dirname’]
- pwd(parameter_s='')
Return the current working directory path.
Examples
In[9]:pwdOut[9]:'/home/tsuser/sprint/ipython'
- pycat(parameter_s='')
Show a syntax-highlighted file through a pager.
This magic is similar to the cat utility, but it will assume the fileto be Python source and will show it with syntax highlighting.
This magic command can either take a local filename, an url,an history range (see %history) or a macro as argument.
If no parameter is given, prints out history of current session up tothis point.
%pycatmyscript.py%pycat7-27%pycatmyMacro%pycathttp://www.example.com/myscript.py
- rehashx(parameter_s='')
Update the alias table with all executable files in $PATH.
rehashx explicitly checks that every entry in $PATH is a filewith execute access (os.X_OK).
Under Windows, it checks executability as a match against a‘|’-separated string of extensions, stored in the IPython configvariable win_exec_ext. This defaults to ‘exe|com|bat’.
This function also resets the root module cache of module completer,used on slow filesystems.
- sc(parameter_s='')
Shell capture - run shell command and capture output (DEPRECATED use !).
DEPRECATED. Suboptimal, retained for backwards compatibility.
You should use the form ‘var = !command’ instead. Example:
“%sc -l myfiles = ls ~” should now be written as
“myfiles = !ls ~”
myfiles.s, myfiles.l and myfiles.n still apply as documentedbelow.
–%sc [options] varname=command
IPython will run the given command using commands.getoutput(), andwill then update the user’s interactive namespace with a variablecalled varname, containing the value of the call. Your command cancontain shell wildcards, pipes, etc.
The ‘=’ sign in the syntax is mandatory, and the variable name yousupply must follow Python’s standard conventions for valid names.
(A special format without variable name exists for internal use)
Options:
-l: list output. Split the output on newlines into a list beforeassigning it to the given variable. By default the output is storedas a single string.
-v: verbose. Print the contents of the variable.
In most cases you should not need to split as a list, because thereturned value is a special type of string which can automaticallyprovide its contents either as a list (split on newlines) or as aspace-separated string. These are convenient, respectively, eitherfor sequential processing or to be passed to a shell command.
For example:
# Capture into variable aIn [1]: sc a=ls *py# a is a string with embedded newlinesIn [2]: aOut[2]: 'setup.py\nwin32_manual_post_install.py'# which can be seen as a list:In [3]: a.lOut[3]: ['setup.py', 'win32_manual_post_install.py']# or as a whitespace-separated string:In [4]: a.sOut[4]: 'setup.py win32_manual_post_install.py'# a.s is useful to pass as a single command line:In [5]: !wc -l $a.s 146 setup.py 130 win32_manual_post_install.py 276 total# while the list form is useful to loop over:In [6]: for f in a.l: ...: !wc -l $f ...:146 setup.py130 win32_manual_post_install.py
Similarly, the lists returned by the -l option are also special, inthe sense that you can equally invoke the .s attribute on them toautomatically get a whitespace-separated string from their contents:
In[7]:sc-lb=ls*pyIn[8]:bOut[8]:['setup.py','win32_manual_post_install.py']In[9]:b.sOut[9]:'setup.py win32_manual_post_install.py'
In summary, both the lists and strings used for output capture havethe following special attributes:
.l(or.list):valueaslist..n(or.nlstr):valueasnewline-separatedstring..s(or.spstr):valueasspace-separatedstring.
- set_env(parameter_s)
Set environment variables. Assumptions are that either “val” is aname in the user namespace, or val is something that evaluates to astring.
- Usage:
%set_envvarval:set value for var
%set_envvar=val:set value for var
%set_envvar=$val:set value for var, using python expansion if possible
- sx(line='',cell=None)
Shell execute - run shell command and capture output (!! is short-hand).
%sx command
IPython will run the given command using commands.getoutput(), andreturn the result formatted as a list (split on ‘n’). Since theoutput is _returned_, it will be stored in ipython’s regular outputcache Out[N] and in the ‘_N’ automatic variables.
Notes:
1) If an input line begins with ‘!!’, then %sx is automaticallyinvoked. That is, while:
!ls
causes ipython to simply issue system(‘ls’), typing:
!!ls
is a shorthand equivalent to:
%sxls
2) %sx differs from %sc in that %sx automatically splits into a list,like ‘%sc -l’. The reason for this is to make it as easy as possibleto process line-oriented shell output via further python commands.%sc is meant to provide much finer control, but requires moretyping.
3) Just like %sc -l, this is a list with special attributes:
.l(or.list):valueaslist..n(or.nlstr):valueasnewline-separatedstring..s(or.spstr):valueaswhitespace-separatedstring.
This is very useful when trying to use such lists as arguments tosystem commands.
- system(line='',cell=None)
Shell execute - run shell command and capture output (!! is short-hand).
%sx command
IPython will run the given command using commands.getoutput(), andreturn the result formatted as a list (split on ‘n’). Since theoutput is _returned_, it will be stored in ipython’s regular outputcache Out[N] and in the ‘_N’ automatic variables.
Notes:
1) If an input line begins with ‘!!’, then %sx is automaticallyinvoked. That is, while:
!ls
causes ipython to simply issue system(‘ls’), typing:
!!ls
is a shorthand equivalent to:
%sxls
2) %sx differs from %sc in that %sx automatically splits into a list,like ‘%sc -l’. The reason for this is to make it as easy as possibleto process line-oriented shell output via further python commands.%sc is meant to provide much finer control, but requires moretyping.
3) Just like %sc -l, this is a list with special attributes:
.l(or.list):valueaslist..n(or.nlstr):valueasnewline-separatedstring..s(or.spstr):valueaswhitespace-separatedstring.
This is very useful when trying to use such lists as arguments tosystem commands.
- unalias(parameter_s='')
Remove an alias
- writefile(line,cell)
%writefile[-a]filename
Write the contents of the cell to a file.
The file will be overwritten unless the -a (–append) flag is specified.
- positional arguments:
filename file to write
- options:
- -a,--append
Append contents of the cell to an existing file. The file willbe created if it does not exist.