src.nuke_tools

Send code from Sublime Text to Nuke to be executed over the tcp network.

View Source
  0"""Send code from Sublime Text to Nuke to be executed over the tcp network."""
  1
  2import os
  3import json
  4import socket
  5import configparser
  6
  7from datetime import datetime
  8
  9NSS_CONFIG = os.path.join(
 10    os.path.expanduser('~'), '.nuke', 'NukeServerSocket.ini'
 11)
 12
 13
 14def format_output(text):
 15    """Format output to send at console.
 16
 17    Example: `[17:49:25] [NukeTools] Hello World`
 18
 19    Args:
 20        text (str): str to be formatted.
 21
 22    Returns:
 23        str: formatted string.
 24    """
 25    now = datetime.now()
 26    time = now.strftime("%H:%M:%S")
 27    return "[{}] [NukeTools] {}".format(time, text)
 28
 29
 30def nss_ip_port():
 31    """Get NukeServerSocket ip port from configuration file.
 32
 33    Get the ip port from NukeServerSocket.ini inside the `$HOME/.nuke/` folder.
 34    If file does not yet exists or the configuration value is absent, will
 35    return a default value of: `54321`, that is also the default value of
 36    NukeServerSocket.
 37
 38    Returns:
 39        int: tcp port value to connect the socket client.
 40    """
 41    try:
 42        config = configparser.ConfigParser()
 43        config.read(NSS_CONFIG)
 44        return int(config['server']['port'])
 45    except KeyError:
 46        # file doesn't exists yet or value is absent
 47        return 54321
 48
 49
 50def prepare_data(data, file=''):
 51    """Prepare the data to be send over the network.
 52
 53    Data should be wrappend inside a stringified array with the key `text` with
 54    the code to execute and an optional key `file` for the file that is being
 55    executed.
 56
 57    Args:
 58        data (str): The data to send.
 59        file (str): Optional. The file that is being executed.
 60
 61    Returns:
 62        str: stringified array.
 63    """
 64    data = {"text": data, "file": file}
 65    return json.dumps(data)
 66
 67
 68def _err_msg(err, hostname, port):
 69    """Generate template error message.
 70
 71    Generate a template error message with the hostname and the port:
 72    `ConnectionError. 192.168.1.50:55555`.
 73
 74    Args:
 75        err (str): Error message to add.
 76        hostname (str): hostname.
 77        port (str|int): port.
 78
 79    Returns:
 80       str: the error message created.
 81    """
 82    err = "{}. {}:{}.\n".format(err, hostname, port)
 83    err += (
 84        'Check Sublime settings if you specified manually the address,'
 85        ' or check if plugin inside Nuke is connected.'
 86    )
 87    return err
 88
 89
 90def send_data(hostname, port, data, timeout=10.0):
 91    """Send data over tcp network.
 92
 93    Send some text data via TCP connection to the host and port specified. Once
 94    the output is ready, will be returned as a string.
 95
 96    Args:
 97        hostname (str): The name of the host.
 98        port (int): The port number.
 99        data (data): The data to send.
100        timeout (float): Timeout connection for the socket. Defaults to: 10.0.
101
102    Returns:
103        str: If socket succeeded will return the received data, otherwise a
104        status message signaling what went wrong.
105    """
106    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as _socket:
107
108        # set a connection timeout in case host is down.
109        _socket.settimeout(timeout)
110
111        try:
112            # connection host and port must match whats inside Nuke
113            _socket.connect((hostname, port))
114        except ConnectionRefusedError:
115            output = _err_msg("ConnectionRefusedError", hostname, port)
116        except socket.timeout:
117            output = _err_msg("ConnectionTimeoutError", hostname, port)
118        except socket.error as err:
119            output = _err_msg("UnknownError: {}".format(err), hostname, port)
120        except Exception as err:  # skipcq: PYL-W0703
121            output = "UnknownException: {}".format(err)
122        else:
123            _socket.sendall(bytearray(data, encoding='utf-8'))
124
125            # the returned data from NukeServerSocket
126            output = _socket.recv(2048).decode('utf-8')
127
128        return format_output(output)
#   def format_output(text):
View Source
15def format_output(text):
16    """Format output to send at console.
17
18    Example: `[17:49:25] [NukeTools] Hello World`
19
20    Args:
21        text (str): str to be formatted.
22
23    Returns:
24        str: formatted string.
25    """
26    now = datetime.now()
27    time = now.strftime("%H:%M:%S")
28    return "[{}] [NukeTools] {}".format(time, text)

Format output to send at console.

Example: [17:49:25] [NukeTools] Hello World

Args: text (str): str to be formatted.

Returns: str: formatted string.

#   def nss_ip_port():
View Source
31def nss_ip_port():
32    """Get NukeServerSocket ip port from configuration file.
33
34    Get the ip port from NukeServerSocket.ini inside the `$HOME/.nuke/` folder.
35    If file does not yet exists or the configuration value is absent, will
36    return a default value of: `54321`, that is also the default value of
37    NukeServerSocket.
38
39    Returns:
40        int: tcp port value to connect the socket client.
41    """
42    try:
43        config = configparser.ConfigParser()
44        config.read(NSS_CONFIG)
45        return int(config['server']['port'])
46    except KeyError:
47        # file doesn't exists yet or value is absent
48        return 54321

Get NukeServerSocket ip port from configuration file.

Get the ip port from NukeServerSocket.ini inside the $HOME/.nuke/ folder. If file does not yet exists or the configuration value is absent, will return a default value of: 54321, that is also the default value of NukeServerSocket.

Returns: int: tcp port value to connect the socket client.

#   def prepare_data(data, file=''):
View Source
51def prepare_data(data, file=''):
52    """Prepare the data to be send over the network.
53
54    Data should be wrappend inside a stringified array with the key `text` with
55    the code to execute and an optional key `file` for the file that is being
56    executed.
57
58    Args:
59        data (str): The data to send.
60        file (str): Optional. The file that is being executed.
61
62    Returns:
63        str: stringified array.
64    """
65    data = {"text": data, "file": file}
66    return json.dumps(data)

Prepare the data to be send over the network.

Data should be wrappend inside a stringified array with the key text with the code to execute and an optional key file for the file that is being executed.

Args: data (str): The data to send. file (str): Optional. The file that is being executed.

Returns: str: stringified array.

#   def send_data(hostname, port, data, timeout=10.0):
View Source
 91def send_data(hostname, port, data, timeout=10.0):
 92    """Send data over tcp network.
 93
 94    Send some text data via TCP connection to the host and port specified. Once
 95    the output is ready, will be returned as a string.
 96
 97    Args:
 98        hostname (str): The name of the host.
 99        port (int): The port number.
100        data (data): The data to send.
101        timeout (float): Timeout connection for the socket. Defaults to: 10.0.
102
103    Returns:
104        str: If socket succeeded will return the received data, otherwise a
105        status message signaling what went wrong.
106    """
107    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as _socket:
108
109        # set a connection timeout in case host is down.
110        _socket.settimeout(timeout)
111
112        try:
113            # connection host and port must match whats inside Nuke
114            _socket.connect((hostname, port))
115        except ConnectionRefusedError:
116            output = _err_msg("ConnectionRefusedError", hostname, port)
117        except socket.timeout:
118            output = _err_msg("ConnectionTimeoutError", hostname, port)
119        except socket.error as err:
120            output = _err_msg("UnknownError: {}".format(err), hostname, port)
121        except Exception as err:  # skipcq: PYL-W0703
122            output = "UnknownException: {}".format(err)
123        else:
124            _socket.sendall(bytearray(data, encoding='utf-8'))
125
126            # the returned data from NukeServerSocket
127            output = _socket.recv(2048).decode('utf-8')
128
129        return format_output(output)

Send data over tcp network.

Send some text data via TCP connection to the host and port specified. Once the output is ready, will be returned as a string.

Args: hostname (str): The name of the host. port (int): The port number. data (data): The data to send. timeout (float): Timeout connection for the socket. Defaults to: 10.0.

Returns: str: If socket succeeded will return the received data, otherwise a status message signaling what went wrong.