pyscripting is python module that provides various utilities to make shell scripting with python easier.
pip install pyscripting
Create your python shell script myscript.py:
#!/usr/bin/env python from scripting import sh sh.ls('-l')
Use your script:
chmod +x myscript.py ./myscript.py
Calling external commands
There are three ways to call external commands.
If possible, python replacement of an external command will be used. Replacements will not be used only in direct calling.
For all replaced commands see Replaced commands.
Returns exit code.
Returns exit code.
Call and return output
Returns stripped stdout (stderr will not be included).
Using this method, output of command will not be printed to stdout. Before returning output, leading white spaces will be stripped.
Don't use this method for large outputs.
output = sh.get('ls', '-l') print('Output was: %s' % output)
You can access arguments passed to script using argv property:
sh.argv - called script name sh.argv - first argument
To avoid overhead and for simplicity reasons, some external commands was replaced by python's internal functions, which works much faster, that calling external command.
Same as external basename.
- Same as external exit.
Similar to external find command.
Returns iterator of all found files.
for f in sh.find(type='f', exclude=['*.pyc']): print(f)
- Same as external mkdir.
- Same as external mkdir -p.
Similar to external test.
if sh.test('-d', '/tmp'): print('/tmp is directory.')
#!/usr/bin/env python from scripting import sh, Makefile make = Makefile(sh) @make('/tmp/myfile.txt') def myrule(target): sh.touch(target) @make() def main(target): myrule() make.run(main)
Last line make.run(main) checks sys.argv and executes specified rule or default if no particular rule is specified. myrule will be executed only, if target file /tmp/myfile.txt does not exists.:
Now call particular rule: