API Reference

Alfred offers APIs to write commands, reuse existing commands, … It aim to make your commands easy to read, write and maintain.

API to write command

The following methods are used to set up a command that you can use through alfred.

alfred.command(name: str, help: str = '', **attrs: Any)

Declare a command.

The command must be created in a module that Alfred references (see Project > Section [alfred.project] > command). When executing, Alfred will reference this command by name and execute it if called.

>>> @alfred.command("hello_world")
>>> def hello_world():
>>>     print("hello world")

help attribute allow you to configure the inline documentation.

>>> @alfred.command("hello_world", help="This is a hello world command")
>>> def hello_world():
>>>     print("hello world")
Parameters:
alfred.option(option: str, option_alias: Optional[str] = None, help: str = '', default: Optional[str] = None, **attrs)

Declare optional parameter on a command

This command can be called either with alfred hello_world, or with alfred hello_world --name=alfred, or with alfred hello_world -n alfred.

>>> import alfred
>>>
>>> @alfred.command("hello_world")
>>> @alfred.option("--name", "-n", help="Name of the person to greet", default="world")
>>> def hello_world(name: str):
>>>     print("hello {name}")
Parameters:
  • option – option name (–option)

  • option_alias – short option (-o)

  • help – inline documentation

  • default – default value if option is not provided (None by default)

:param allow to use any click supported attributes (see https://click.palletsprojects.com/en/latest/api/), support is not garanteed in long term

alfred.sh(command: Union[str, List[str]], fail_message: str = None) Command

Load an executable program from the local system. If the command does not exists, it will show an error fail_message to the console.

>>> echo = alfred.sh("echo", "echo is missing on your system")
>>> alfred.run(echo, ["hello", "world"])

If many commands are provided as command name, it will try the command one by one until one of them is present on the system. This behavior is require when you target different platform for example (Ubuntu is using open to open an url, when MacOs support xdg-open with the same behavior)

>>> open = alfred.sh(["open", "xdg-open"], "Either open, either xdg-open is missing on your system. Are you using a compatible platform ?")  # pylint: disable=line-too-long
>>> alfred.run(open, "http://www.github.com")
Parameters:
  • command – command or list of command name to lookup

  • fail_message – failure message show to the user if no command has been found

Returns:

a command you can use with alfred.run

alfred.run(command: Union[str, Command], args: Optional[Union[str, List[str]]] = None, exit_on_error=True, stream_stdout=True, stream_stderr=True) Tuple[int, str, str]

Most of the process run by alfred are supposed to stop if the excecution process is finishing with an exit code of 0

There is one or two exception as the execution of migration by alembic through honcho. exit_on_error allow to manage them

>>> echo = alfred.sh("echo", "echo is missing on your system")
>>> alfred.run(echo, ["hello", "world"])

The flag exit_on_error is set to True by default. If you want to ignore the exit code and continue the execution even if the execution has failed, you can set it to False.

>>> ls = alfred.sh("ls", "ls is missing on your system")
>>> mv = alfred.sh("mv", "mv is missing on your system")
>>> alfred.run(ls, ["/var/yolo"], exit_on_error=False)
>>> alfred.run(mv, ["/var/yolo", "/var/yolo1"], exit_on_error=False)

The stdout is displayed by default. You can use the flag stream_stdout to hide the output from terminal. It’s useful when you run a command and parse its result.

>>> alfred.run("ls /var/yolo", stream_stdout=False)

The stderr is displayed by default. You can use the flag stream_stderr to hide the error output from terminal. It’s not recommanded if you keep the error_on_exit to True.

>>> alfred.run("ls /var/yolo", stream_stderr=False)

A text command can be used directly with alfred.run. The text command is parsed and the execute is extracted from first element in text. The arguments are extracted from the other elements.

>>> alfred.run("echo hello world")
>>> alfred.run('cp "/home/fabien/hello world" /tmp', exit_on_error=False)

Shell operations are not supported &, |, &&, ||, etc… You can not use for example echo hello world | grep hello or echo hello world > file.txt. If you use it an error will be raised.

The return code, the stdout and the stderr are returned as a tuple.

>>> return_code, stdout, stderr = alfred.run("echo hello world")
Parameters:
  • command – command or text program to execute

  • exit_on_error – break the flow if the exit code is different of 0 (active by default)

  • stream_stdout – stream the command output in the terminal (enable by default)

  • stream_stderr – stream the command errors in the terminal (enable by default)

alfred.invoke_command(ctx, command: str, **kwargs) None

Invokes an existing command as a subcommand. This instruction offer the perfect way to build pipelines

>>> alfred.invoke_command("test"])

Command arguments are passed as named parameters.

>>> alfred.invoke_command("hello_world", name="fabien"])

To invoke a command from a sub-project, it is possible to pass the fullname of a command as an array as an argument.

>>> alfred.invoke_command(["product1", "hello_world"], name="fabien"])
alfred.CMD_RUNNING()

Isolates heavy dependencies to speed up command discovery on alfred and alfred --help.

They are loaded when the user executes a module module command.

>>> if alfred.CMD_RUNNING():
>>>     import torch
>>>
>>> @alfred.command("use_torch")
>>> def use_torch():
>>>     example_list = [1,2,3]
>>>     x = torch.tensor(example_list)
>>>     print(x)
alfred.pythonpath(directories: List[str] = None, append_project=True)

Add the project folder, i.e. the root folder which corresponds to the alfred command used, to pythonpath to make available the packages present at this level.

>>> @alfred.command()
>>> @alfred.pythonpath()
>>> def my_command():
>>>     pass

It is possible to add other directories to the pythonpath with the directories parameter. The path of the added folders is relative to the root folder of the alfred command used, ie the location of the .alfred.yml file.

>>> @alfred.command()
>>> @alfred.pythonpath(['src'])
>>> def my_command():
>>>     pass
alfred.env(**kwargs) None

Assign environment variables in a command

>>> with alfred.env(ENV="prod"):
>>>     echo = alfred.sh("echo")
>>>     echo("hello world")

API to ask information to the user

alfred.prompt(label: str, proposals: Optional[List[str]] = None, default: Optional[str] = None, validation_func: Optional[Callable[[str], Optional[str]]] = None) str

Prompt the user for an input

>>> alfred.prompt("What is your name ?")
>>> alfred.prompt("Where were you born ?", proposals=["France", "Other"], default="France")
>>> alfred.prompt("What is your name ?", validation_func=lambda name: "Name is required" if name == "" else None)
Parameters:
  • label – the question asked to the user

  • proposals – the proposals displayed to the user in auto-completion

  • default – the default value if the user leaves the field empty

  • validation_func – a function that validates the user input

Returns:

the user input

alfred.confirm(question: str, default: str = 'n') bool

Ask the user for a confirmation

>>> alfred.confirm("Are you sure ?")
>>> alfred.confirm("Are you sure ?", default="y")
Parameters:
  • question – the question asked to the user

  • default – the default value if the user leaves the field empty

Returns:

True if the user confirmed, False otherwise

API to check environment

alfred.is_posix() bool

returns true if the machine executing the code is using linux based os or mac os

>>> if alfred.is_posix():
>>>     print("do something for linux and macos"
alfred.is_windows() bool

returns true if the machine executing the code is under windows

>>> if alfred.is_windows():
>>>     print("do something for windows"
alfred.is_linux() bool

returns true if the machine executing the code is using linux based os

>>> if alfred.is_linux():
>>>     print("do something for ubuntu, debian, ..."
alfred.is_macos() bool

returns true if the machine executing the code is using macos

>>> if alfred.is_macos():
>>>     print("do something for macos"
alfred.project_directory() str

Returns the project directory of alfred relative to the current command. This is the first parent where the .alfred.toml file is present.

>>> @alfred.command("project_directory")
>>> def project_directory_command():
>>>     project_directory = alfred.project_directory()
>>>     print(project_directory)
alfred.execution_directory() str

Returns the directory from which the command is executed.

The working folder return by os.getcwd is set to the project directory inside a command. This allows to change the path in commands knowing where the working directory is.

The project directory is the first parent where the .alfred.toml file is present.

>>> @alfred.command("execution_directory")
>>> def execution_directory_command():
>>>     execution_directory = alfred.execution_directory()
>>>     print(execution_directory)