newportxps 0.3.0__py3-none-any.whl → 2025.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
newportxps/__init__.py CHANGED
@@ -1 +1,3 @@
1
+ from .version import __version__, __version_tuple__
2
+
1
3
  from .newportxps import NewportXPS
@@ -0,0 +1,107 @@
1
+ #!/usr/bin/env python
2
+
3
+ import time
4
+ import sys
5
+ from tabulate import tabulate
6
+
7
+ class DebugTimer():
8
+ '''
9
+ Measure run times for lines of code and summarize results
10
+ '''
11
+ def __init__(self, initial_message=None, verbose=False,
12
+ with_mod_count=False, precision=3):
13
+ self.verbose = verbose
14
+ self.precision = precision
15
+ self.with_mod_count = with_mod_count
16
+ self.clear(initial_message=initial_message)
17
+
18
+ def clear(self, initial_message=None):
19
+ self.data = []
20
+ if initial_message is None:
21
+ initial_message = 'DebugTimer'
22
+ self.add(f'initial_message {time.ctime()}')
23
+
24
+ def add(self, msg=None):
25
+ if msg is None:
26
+ msg = time.ctime()
27
+ self.data.append((msg, len(sys.modules), time.perf_counter()))
28
+ if self.verbose:
29
+ print(msg)
30
+
31
+ def get_table(self, precision=None, with_mod_count=True,
32
+ tablefmt='simple_outline'):
33
+ prec = self.precision
34
+ if precision is not None:
35
+ prec = precision
36
+ with_nmod= self.with_mod_count
37
+ if with_mod_count is not None:
38
+ with_nmod = with_mod_count
39
+ m0, n0, t0 = self.data[0]
40
+ tprev= t0
41
+ header = ['Message','Delta Time', 'Total Time']
42
+ row = [m0, 0, 0]
43
+ if with_nmod:
44
+ header.append('# Modules')
45
+ row.append(n0)
46
+ table = [row[:]]
47
+ for m, n, t in self.data[1:]:
48
+ tt, dt = t-t0, t-tprev
49
+ row = [m, dt, tt, n] if with_nmod else [m, dt, tt]
50
+ table.append(row[:])
51
+ tprev = t
52
+ ffmt = f'.{prec}f'
53
+ return tabulate(table, header, floatfmt=ffmt, tablefmt=tablefmt)
54
+
55
+ def show(self, precision=None, with_mod_count=True,
56
+ tablefmt='outline'):
57
+ print(self.get_table(precision=precision,
58
+ with_mod_count=with_mod_count,
59
+ tablefmt=tablefmt))
60
+
61
+
62
+ def debugtimer(initial_message=None, with_mod_count=False,
63
+ verbose=False, precision=3):
64
+ '''debugtimer returns a DebugTimer object to measure the runtime of
65
+ portions of code, and then write a simple report of the results.
66
+
67
+ Arguments
68
+ ------------
69
+ iniitial message: str, optional initial message ['DebugTimer']
70
+ precision: int, precision for timing results [3]
71
+ with_mod_count: bool, whether to include number of imported modules [True]
72
+ verbose: bool, whether to print() each message when entered [False]
73
+
74
+ Returns
75
+ --------
76
+ DebugTimer object, with methods:
77
+
78
+ clear(initial_message=None) -- reset Timer
79
+ add(message) -- record time, with message
80
+ show(tablefmt='simple_outline') -- print timer report
81
+ where tableftmt can be any tablefmt for the tabulate module.
82
+
83
+ Example:
84
+ -------
85
+ timer = debugtimer('started timer', precision=4)
86
+ result = foo(x=100)
87
+ timer.add('ran foo')
88
+ bar(result)
89
+ timer.add('ran bar')
90
+ timer.show(tablefmt='outline')
91
+ '''
92
+ return DebugTimer(initial_message=initial_message,
93
+ with_mod_count=with_mod_count,
94
+ verbose=verbose, precision=precision)
95
+
96
+
97
+ if __name__ == '__main__':
98
+ dt = debugtimer('test timer')
99
+ time.sleep(1.102)
100
+ dt.add('slept for 1.102 seconds')
101
+ import numpy as np
102
+ n = 10_000_000
103
+ x = np.arange(n, dtype='float64')/3.0
104
+ dt.add(f'created numpy array len={n}')
105
+ s = np.sqrt(x)
106
+ dt.add('took sqrt')
107
+ dt.show(tablefmt='outline')
newportxps/ftp_wrapper.py CHANGED
@@ -9,6 +9,15 @@ logger = logging.getLogger('paramiko')
9
9
  logger.setLevel(logging.ERROR)
10
10
 
11
11
 
12
+ SFTP_ERROR_MESSAGE = """Could not connect to XPS with sftp: no host key.
13
+
14
+ You may need to add a host key to your `ssh known_hosts` file, using
15
+ ssh-keyscan {host} >> ~/.ssh/known_hosts
16
+
17
+ or first connecting with `sftp Administrator@{host}` """
18
+
19
+ import paramiko
20
+
12
21
  HAS_PYSFTP = False
13
22
  try:
14
23
  import pysftp
@@ -53,7 +62,9 @@ class FTPBaseWrapper(object):
53
62
  class SFTPWrapper(FTPBaseWrapper):
54
63
  """wrap ftp interactions for Newport XPS models D"""
55
64
  def __init__(self, host=None, username='Administrator',
56
- password='Administrator'):
65
+ password='Administrator', use_paramiko=True):
66
+ self.use_paramiko = use_paramiko
67
+ self.ssh_client = None
57
68
  FTPBaseWrapper.__init__(self, host=host,
58
69
  username=username, password=password)
59
70
 
@@ -64,19 +75,32 @@ class SFTPWrapper(FTPBaseWrapper):
64
75
  self.username = username
65
76
  if password is not None:
66
77
  self.password = password
78
+ if not self.use_paramiko and HAS_PYSFTP:
79
+ self._conn = pysftp.Connection(host,
80
+ username=username,
81
+ password=password)
82
+ else:
83
+ if self.ssh_client is None:
84
+ self.ssh_client = paramiko.SSHClient()
85
+ self.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
86
+
87
+ try:
88
+ self.ssh_client.connect(host, 22, username, password)
89
+
90
+ except paramiko.AuthenticationException:
91
+ print("Authentication failed. Check your username and password/key.")
92
+ raise ValueError(SFTP_ERROR_MESSAGE.format(host=self.host))
93
+ except paramiko.SSHException as e:
94
+ print(f"SSH connection error: {e}")
95
+ raise ValueError(SFTP_ERROR_MESSAGE.format(host=self.host))
96
+ finally:
97
+ self._conn = self.ssh_client.open_sftp()
67
98
 
68
- if not HAS_PYSFTP:
69
- raise ValueError("pysftp not installed.")
70
- try:
71
- self._conn = pysftp.Connection(self.host,
72
- username=self.username,
73
- password=self.password)
74
- except:
75
- print("ERROR: sftp connection to %s failed" % self.host)
76
- print("You may need to add the host keys for your XPS to your")
77
- print("ssh known_hosts file, using a command like this:")
78
- print(" ssh-keyscan %s >> ~/.ssh/known_hosts" % self.host)
79
-
99
+ def cwd(self, remotedir):
100
+ if self.use_paramiko:
101
+ self._conn.chdir(remotedir)
102
+ elif hasattr(self._conn, 'cwd'):
103
+ self._conn.cwd(remotedir)
80
104
 
81
105
  def save(self, remotefile, localfile):
82
106
  "save remote file to local file"