Here are the examples of the python api sys.platform.lower.startswith taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
46 Examples
3
Example 1
Project: pexpect Source File: test_expect.py
def test_expect_setecho_off(self):
'''This tests that echo may be toggled off.
'''
p = pexpect.spawn('cat', echo=True, timeout=5)
try:
self._expect_echo_toggle(p)
except IOError:
if sys.platform.lower().startswith('sunos'):
if hasattr(unittest, 'SkipTest'):
raise unittest.SkipTest("Not supported on this platform.")
return 'skip'
raise
3
Example 2
Project: pexpect Source File: test_expect.py
def test_expect_setecho_off_exact(self):
p = pexpect.spawn('cat', echo=True, timeout=5)
p.expect = p.expect_exact
try:
self._expect_echo_toggle(p)
except IOError:
if sys.platform.lower().startswith('sunos'):
if hasattr(unittest, 'SkipTest'):
raise unittest.SkipTest("Not supported on this platform.")
return 'skip'
raise
3
Example 3
Project: pexpect Source File: test_expect.py
def test_waitnoecho(self):
" Tests setecho(False) followed by waitnoecho() "
p = pexpect.spawn('cat', echo=False, timeout=5)
try:
p.setecho(False)
p.waitnoecho()
except IOError:
if sys.platform.lower().startswith('sunos'):
if hasattr(unittest, 'SkipTest'):
raise unittest.SkipTest("Not supported on this platform.")
return 'skip'
raise
3
Example 4
Project: pexpect Source File: test_isalive.py
def test_expect_isalive_dead_after_SIGHUP(self):
p = pexpect.spawn('cat', timeout=5, ignore_sighup=False)
assert p.isalive()
force = False
if sys.platform.lower().startswith('sunos'):
# On Solaris (SmartOs), and only when executed from cron(1), SIGKILL
# is required to end the sub-process. This is done using force=True
force = True
assert p.terminate(force) == True
p.expect(pexpect.EOF)
assert not p.isalive()
3
Example 5
Project: pexpect Source File: test_isalive.py
def test_expect_isalive_dead_after_SIGINT(self):
p = pexpect.spawn('cat', timeout=5)
assert p.isalive()
force = False
if sys.platform.lower().startswith('sunos'):
# On Solaris (SmartOs), and only when executed from cron(1), SIGKILL
# is required to end the sub-process. This is done using force=True
force = True
assert p.terminate(force) == True
p.expect(pexpect.EOF)
assert not p.isalive()
3
Example 6
def test_isatty(self):
" Test isatty() is True after spawning process on most platforms. "
child = pexpect.spawn('cat')
if not child.isatty() and sys.platform.lower().startswith('sunos'):
if hasattr(unittest, 'SkipTest'):
raise unittest.SkipTest("Not supported on this platform.")
return 'skip'
assert child.isatty()
3
Example 7
Project: pexpect Source File: test_unicode.py
def test_expect_setecho_toggle(self):
'''This tests that echo may be toggled off.
'''
p = pexpect.spawnu('cat', timeout=5)
try:
self._expect_echo_toggle_off(p)
except IOError:
if sys.platform.lower().startswith('sunos'):
if hasattr(unittest, 'SkipTest'):
raise unittest.SkipTest("Not supported on this platform.")
return 'skip'
raise
self._expect_echo_toggle_on(p)
3
Example 8
Project: pexpect Source File: test_unicode.py
def test_expect_setecho_toggle_exact(self):
p = pexpect.spawnu('cat', timeout=5)
p.expect = p.expect_exact
try:
self._expect_echo_toggle_off(p)
except IOError:
if sys.platform.lower().startswith('sunos'):
if hasattr(unittest, 'SkipTest'):
raise unittest.SkipTest("Not supported on this platform.")
return 'skip'
raise
self._expect_echo_toggle_on(p)
3
Example 9
def get_multiarch():
if not sys.platform.lower().startswith('linux'):
return ''
# this function returns the suffix for lib directories on supported systems or an empty string
# it uses two step approach to look for multiarch: first run gcc -print-multiarch and if
# failed try to run dpkg-architecture
p = subprocess.Popen(
['gcc', '-print-multiarch'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
if p.returncode != 0:
out, err = subprocess.Popen(
['dpkg-architecture', '-qDEB_HOST_MULTIARCH'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
# be sure of returning empty string or a valid multiarch tuple format
assert(not out.strip() or out.strip().count('-') == 2)
return out.strip()
3
Example 10
Project: benchbase Source File: util.py
def gnuplot(script_path):
"""Execute a gnuplot script."""
path = os.path.dirname(os.path.abspath(script_path))
if sys.platform.lower().startswith('win'):
# commands module doesn't work on win and gnuplot is named
# wgnuplot
ret = os.system('cd "%s" && wgnuplot "%s"' %
path, script_path)
if ret != 0:
raise RuntimeError("Failed to run wgnuplot cmd on " +
script_path)
else:
cmd = 'cd %s && gnuplot %s' % (path, os.path.abspath(script_path))
ret, output = getstatusoutput(cmd)
if ret != 0:
print "ERROR on " + cmd
3
Example 11
def __init__(self, options, conf_file="siteconf.py", conf_dir="."):
self.optdict = dict((opt.name, opt) for opt in options)
self.options = options
self.conf_dir = conf_dir
self.conf_file = conf_file
from os.path import expanduser
self.user_conf_file = expanduser("~/.aksetup-defaults.py")
import sys
if not sys.platform.lower().startswith("win"):
self.global_conf_file = "/etc/aksetup-defaults.py"
else:
self.global_conf_file = None
3
Example 12
Project: xraylarch Source File: site_config.py
def system_settings():
"""set system-specific Environmental Variables, and make sure
that the user larchdirs exist.
This is run by the interpreter on startup."""
# ubuntu / unity hack
if sys.platform.lower().startswith('linux'):
if 'ubuntu' in os.uname()[3].lower():
os.environ['UBUNTU_MENUPROXY'] = '0'
make_user_larchdirs()
3
Example 13
Project: xraylarch Source File: periodictable.py
def __init__(self, parent, title='Select Element',
onselect=None, tooltip_msg=None, size=(-1, -1), **kws):
wx.Panel.__init__(self, parent, -1, size=size, name='PeriodicTable', **kws)
self.parent = parent
self.onselect = onselect
self.tooltip_msg = tooltip_msg
self.wids = {}
self.ctrls = {}
self.SetBackgroundColour(self.FRAME_BG)
self.selected = None
self.titlefont = wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD)
self.elemfont = wx.Font( 9, wx.SWISS, wx.NORMAL, wx.NORMAL)
self.subtitlefont = wx.Font( 7, wx.DEFAULT, wx.NORMAL, wx.BOLD)
if sys.platform.lower().startswith('win'):
self.elemfont = wx.Font( 8, wx.SWISS, wx.NORMAL, wx.BOLD)
self.subtitlefont = wx.Font( 8, wx.DEFAULT, wx.NORMAL, wx.BOLD)
self.BuildPanel()
3
Example 14
def _prepare(self):
""" Setup initial requirements for daemon run.
"""
super(TaskRunner, self)._prepare()
self._setup_root_plugins()
# set the default x-window display for non-mac systems
if not sys.platform.lower().startswith('darwin'):
if not 'DISPLAY' in os.environ:
os.environ['DISPLAY'] = ':0.0'
3
Example 15
def bar(self, current, total):
if not total:
return '.'
if sys.platform.lower().startswith('win'):
cr = "\r"
else:
cr = chr(27) + "[A\n"
pct = float(current) / total
max_hash = 20
num_hash = int(round(pct * max_hash))
return (" [%s%s] %0.1f%% (%s/estimated %s msgs)%s" %
('#' * num_hash, ' ' * (max_hash - num_hash),
100.0 * pct, current, total, cr))
3
Example 16
Project: PyChecker Source File: setup.py
def get_site_packages_path():
"""
Returns the platform-specific location of the site-packages directory.
This directory is usually something like /usr/share/python2.3/site-packages
on UNIX platforms and /Python23/Lib/site-packages on Windows platforms.
"""
if sys.platform.lower().startswith('win'):
return os.path.join(sys.prefix, "Lib", "site-packages")
else:
return os.path.join(sys.prefix, "lib",
"python%s" % sys.version[:3],
"site-packages")
3
Example 17
def bar(self, current, total):
if not total:
return '.'
if sys.platform.lower().startswith('win'):
cr = "\r"
else:
cr = chr(27) + "[A\n"
pct = float(current) / total
max_hash = 20
num_hash = int(round(pct * max_hash))
return (" [%s%s] %0.1f%% (%s/%s msgs)%s" %
('#' * num_hash, ' ' * (max_hash - num_hash),
100.0 * pct, current, total, cr))
3
Example 18
Project: nupic Source File: syntactic_sugar_test.py
@unittest.skipIf(sys.platform.lower().startswith("win"),
"Not supported on Windows, yet!")
def testRegion(self):
r = net.Network().addRegion('r', 'py.TestNode', '')
print r.spec
self.assertEqual(r.type, 'py.TestNode')
self.assertEqual(r.name, 'r')
self.assertTrue(r.dimensions.isUnspecified())
3
Example 19
Project: nupic Source File: syntactic_sugar_test.py
@unittest.skipIf(sys.platform.lower().startswith("win"),
"Not supported on Windows, yet!")
def testSpec(self):
ns = net.Region.getSpecFromType('py.TestNode')
self.assertEqual(ns.description,
'The node spec of the NuPIC 2 Python TestNode')
n = net.Network()
r = n.addRegion('r', 'py.TestNode', '')
ns2 = r.spec
self.assertEqual(ns.singleNodeOnly, ns2.singleNodeOnly)
self.assertEqual(ns.description, ns2.description)
self.assertEqual(ns.inputs, ns2.inputs)
self.assertEqual(ns.outputs, ns2.outputs)
self.assertEqual(ns.parameters, ns2.parameters)
self.assertEqual(ns.commands, ns2.commands)
3
Example 20
def __init__(self, test_module, test_class, test_name, options,
cycle, cvus, thread_id, thread_signaller, sleep_time,
debug=False, feedback=None):
meta_method_name = mmn_encode(test_name, cycle, cvus, thread_id)
threading.Thread.__init__(self, target=self.run, name=meta_method_name,
args=())
self.test = load_unittest(test_module, test_class, meta_method_name,
options)
if sys.platform.lower().startswith('win'):
self.color = False
else:
self.color = not options.no_color
self.sleep_time = sleep_time
self.debug = debug
self.thread_signaller = thread_signaller
# this makes threads endings if main stop with a KeyboardInterupt
self.setDaemon(1)
self.feedback = feedback
3
Example 21
Project: FunkLoad Source File: ReportRenderHtmlGnuPlot.py
def gnuplot(script_path):
"""Execute a gnuplot script."""
path = os.path.dirname(os.path.abspath(script_path))
if sys.platform.lower().startswith('win'):
# commands module doesn't work on win and gnuplot is named
# wgnuplot
ret = os.system('cd "' + path + '" && wgnuplot "' +
os.path.abspath(script_path) + '"')
if ret != 0:
raise RuntimeError("Failed to run wgnuplot cmd on " +
os.path.abspath(script_path))
else:
cmd = 'cd "' + path + '"; gnuplot "' + os.path.abspath(script_path) + '"'
ret, output = getstatusoutput(cmd)
if ret != 0:
raise RuntimeError("Failed to run gnuplot cmd: " + cmd +
"\n" + str(output))
3
Example 22
def system(self, cmd, expected_code=0):
"""Execute a cmd and exit on fail return cmd output."""
if sys.platform.lower().startswith('win'):
ret = winplatform_getstatusoutput(cmd)
if not ret:
self.fail('Cannot run self.system on windows without the subprocess module (python 2.6)')
else:
ret = commands.getstatusoutput(cmd)
if ret[0] != expected_code:
self.fail("exec [%s] return code %s != %s output:\n%s" %
(cmd, ret[0], expected_code, ret[1]))
return ret[1]
3
Example 23
def test_xmlrpc(self):
# windows os does not support the monitor server
if not sys.platform.lower().startswith('win'):
# extract demo example and run the xmlrpc test
from tempfile import mkdtemp
pwd = os.getcwd()
tmp_path = mkdtemp('funkload')
os.chdir(tmp_path)
self.system('fl-install-demo')
os.chdir(os.path.join(tmp_path, 'funkload-demo', 'xmlrpc'))
self.system("fl-credential-ctl cred.conf restart")
self.system("fl-monitor-ctl monitor.conf restart")
self.system("fl-run-test -v test_Credential.py")
self.system("fl-run-bench -c 1:10:20 -D 4 "
"test_Credential.py Credential.test_credential")
self.system("fl-monitor-ctl monitor.conf stop")
self.system("fl-credential-ctl cred.conf stop")
self.system("fl-build-report credential-bench.xml --html")
os.chdir(pwd)
0
Example 24
Project: pexpect Source File: pty_spawn.py
def __init__(self, command, args=[], timeout=30, maxread=2000,
searchwindowsize=None, logfile=None, cwd=None, env=None,
ignore_sighup=False, echo=True, preexec_fn=None,
encoding=None, codec_errors='strict', dimensions=None):
'''This is the constructor. The command parameter may be a string that
includes a command and any arguments to the command. For example::
child = pexpect.spawn('/usr/bin/ftp')
child = pexpect.spawn('/usr/bin/ssh [email protected]')
child = pexpect.spawn('ls -latr /tmp')
You may also construct it with a list of arguments like so::
child = pexpect.spawn('/usr/bin/ftp', [])
child = pexpect.spawn('/usr/bin/ssh', ['[email protected]'])
child = pexpect.spawn('ls', ['-latr', '/tmp'])
After this the child application will be created and will be ready to
talk to. For normal use, see expect() and send() and sendline().
Remember that Pexpect does NOT interpret shell meta characters such as
redirect, pipe, or wild cards (``>``, ``|``, or ``*``). This is a
common mistake. If you want to run a command and pipe it through
another command then you must also start a shell. For example::
child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > logs.txt"')
child.expect(pexpect.EOF)
The second form of spawn (where you pass a list of arguments) is useful
in situations where you wish to spawn a command and pass it its own
argument list. This can make syntax more clear. For example, the
following is equivalent to the previous example::
shell_cmd = 'ls -l | grep LOG > logs.txt'
child = pexpect.spawn('/bin/bash', ['-c', shell_cmd])
child.expect(pexpect.EOF)
The maxread attribute sets the read buffer size. This is maximum number
of bytes that Pexpect will try to read from a TTY at one time. Setting
the maxread size to 1 will turn off buffering. Setting the maxread
value higher may help performance in cases where large amounts of
output are read back from the child. This feature is useful in
conjunction with searchwindowsize.
When the keyword argument *searchwindowsize* is None (default), the
full buffer is searched at each iteration of receiving incoming data.
The default number of bytes scanned at each iteration is very large
and may be reduced to collaterally reduce search cost. After
:meth:`~.expect` returns, the full buffer attribute remains up to
size *maxread* irrespective of *searchwindowsize* value.
When the keyword argument ``timeout`` is specified as a number,
(default: *30*), then :class:`TIMEOUT` will be raised after the value
specified has elapsed, in seconds, for any of the :meth:`~.expect`
family of method calls. When None, TIMEOUT will not be raised, and
:meth:`~.expect` may block indefinitely until match.
The logfile member turns on or off logging. All input and output will
be copied to the given file object. Set logfile to None to stop
logging. This is the default. Set logfile to sys.stdout to echo
everything to standard output. The logfile is flushed after each write.
Example log input and output to a file::
child = pexpect.spawn('some_command')
fout = open('mylog.txt','wb')
child.logfile = fout
Example log to stdout::
# In Python 2:
child = pexpect.spawn('some_command')
child.logfile = sys.stdout
# In Python 3, spawnu should be used to give str to stdout:
child = pexpect.spawnu('some_command')
child.logfile = sys.stdout
The logfile_read and logfile_send members can be used to separately log
the input from the child and output sent to the child. Sometimes you
don't want to see everything you write to the child. You only want to
log what the child sends back. For example::
child = pexpect.spawn('some_command')
child.logfile_read = sys.stdout
You will need to pass an encoding to spawn in the above code if you are
using Python 3.
To separately log output sent to the child use logfile_send::
child.logfile_send = fout
If ``ignore_sighup`` is True, the child process will ignore SIGHUP
signals. The default is False from Pexpect 4.0, meaning that SIGHUP
will be handled normally by the child.
The delaybeforesend helps overcome a weird behavior that many users
were experiencing. The typical problem was that a user would expect() a
"Password:" prompt and then immediately call sendline() to send the
password. The user would then see that their password was echoed back
to them. Passwords don't normally echo. The problem is caused by the
fact that most applications print out the "Password" prompt and then
turn off stdin echo, but if you send your password before the
application turned off echo, then you get your password echoed.
Normally this wouldn't be a problem when interacting with a human at a
real keyboard. If you introduce a slight delay just before writing then
this seems to clear up the problem. This was such a common problem for
many users that I decided that the default pexpect behavior should be
to sleep just before writing to the child application. 1/20th of a
second (50 ms) seems to be enough to clear up the problem. You can set
delaybeforesend to None to return to the old behavior.
Note that spawn is clever about finding commands on your path.
It uses the same logic that "which" uses to find executables.
If you wish to get the exit status of the child you must call the
close() method. The exit or signal status of the child will be stored
in self.exitstatus or self.signalstatus. If the child exited normally
then exitstatus will store the exit return code and signalstatus will
be None. If the child was terminated abnormally with a signal then
signalstatus will store the signal value and exitstatus will be None::
child = pexpect.spawn('some_command')
child.close()
print(child.exitstatus, child.signalstatus)
If you need more detail you can also read the self.status member which
stores the status returned by os.waitpid. You can interpret this using
os.WIFEXITED/os.WEXITSTATUS or os.WIFSIGNALED/os.TERMSIG.
The echo attribute may be set to False to disable echoing of input.
As a pseudo-terminal, all input echoed by the "keyboard" (send()
or sendline()) will be repeated to output. For many cases, it is
not desirable to have echo enabled, and it may be later disabled
using setecho(False) followed by waitnoecho(). However, for some
platforms such as Solaris, this is not possible, and should be
disabled immediately on spawn.
If preexec_fn is given, it will be called in the child process before
launching the given command. This is useful to e.g. reset inherited
signal handlers.
The dimensions attribute specifies the size of the pseudo-terminal as
seen by the subprocess, and is specified as a two-entry tuple (rows,
columns). If this is unspecified, the defaults in ptyprocess will apply.
'''
super(spawn, self).__init__(timeout=timeout, maxread=maxread, searchwindowsize=searchwindowsize,
logfile=logfile, encoding=encoding, codec_errors=codec_errors)
self.STDIN_FILENO = pty.STDIN_FILENO
self.STDOUT_FILENO = pty.STDOUT_FILENO
self.STDERR_FILENO = pty.STDERR_FILENO
self.cwd = cwd
self.env = env
self.echo = echo
self.ignore_sighup = ignore_sighup
self.__irix_hack = sys.platform.lower().startswith('irix')
if command is None:
self.command = None
self.args = None
self.name = '<pexpect factory incomplete>'
else:
self._spawn(command, args, preexec_fn, dimensions)
0
Example 25
Project: pexpect Source File: test_expect.py
def test_waitnoecho_order(self):
''' This tests that we can wait on a child process to set echo mode.
For example, this tests that we could wait for SSH to set ECHO False
when asking of a password. This makes use of an external script
echo_wait.py. '''
p1 = pexpect.spawn('%s echo_wait.py' % self.PYTHONBIN)
start = time.time()
try:
p1.waitnoecho(timeout=10)
except IOError:
if sys.platform.lower().startswith('sunos'):
if hasattr(unittest, 'SkipTest'):
raise unittest.SkipTest("Not supported on this platform.")
return 'skip'
raise
end_time = time.time() - start
assert end_time < 10 and end_time > 2, "waitnoecho did not set ECHO off in the expected window of time."
# test that we actually timeout and return False if ECHO is never set off.
p1 = pexpect.spawn('cat')
start = time.time()
retval = p1.waitnoecho(timeout=4)
end_time = time.time() - start
assert end_time > 3, "waitnoecho should have waited longer than 2 seconds. retval should be False, retval=%d"%retval
assert retval==False, "retval should be False, retval=%d"%retval
# This one is mainly here to test default timeout for code coverage.
p1 = pexpect.spawn('%s echo_wait.py' % self.PYTHONBIN)
start = time.time()
p1.waitnoecho()
end_time = time.time() - start
assert end_time < 10, "waitnoecho did not set ECHO off in the expected window of time."
0
Example 26
Project: azure-linux-extensions Source File: httpclient.py
def should_use_httplib(self):
if sys.platform.lower().startswith('win') and self.cert_file:
# On Windows, auto-detect between Windows Store Certificate
# (winhttp) and OpenSSL .pem certificate file (httplib).
#
# We used to only support certificates installed in the Windows
# Certificate Store.
# cert_file example: CURRENT_USER\my\CertificateName
#
# We now support using an OpenSSL .pem certificate file,
# for a consistent experience across all platforms.
# cert_file example: account\certificate.pem
#
# When using OpenSSL .pem certificate file on Windows, make sure
# you are on CPython 2.7.4 or later.
# If it's not an existing file on disk, then treat it as a path in
# the Windows Certificate Store, which means we can't use httplib.
if not os.path.isfile(self.cert_file):
return False
return True
0
Example 27
Project: azure-sdk-for-python Source File: servicemanagementclient.py
@staticmethod
def should_use_requests(cert_file):
if sys.platform.lower().startswith('win') and cert_file:
# On Windows, auto-detect between Windows Store Certificate
# (winhttp) and OpenSSL .pem certificate file (httplib).
#
# We used to only support certificates installed in the Windows
# Certificate Store.
# cert_file example: CURRENT_USER\my\CertificateName
#
# We now support using an OpenSSL .pem certificate file,
# for a consistent experience across all platforms.
# cert_file example: account\certificate.pem
#
# When using OpenSSL .pem certificate file on Windows, make sure
# you are on CPython 2.7.4 or later.
# If it's not an existing file on disk, then treat it as a path in
# the Windows Certificate Store, which means we can't use requests.
if not os.path.isfile(cert_file):
return False
return True
0
Example 28
def isWindows(self):
return sys.platform.lower().startswith('win')
0
Example 29
Project: txstatsd Source File: test_process.py
def test_cpu_counters(self):
"""System cpu counters are collected through psutil."""
cpu_times = psutil.cpu_times()
with mock.patch("psutil.cpu_times"):
psutil.cpu_times.return_value = cpu_times
result = report_system_stats()
psutil.cpu_times.assert_called_once_with(percpu=False)
# cpu_times is platform-dependent
if sys.platform.lower().startswith("linux"):
self.assertEqual(cpu_times.user, result["sys.cpu.user"])
self.assertEqual(cpu_times.system, result["sys.cpu.system"])
self.assertEqual(cpu_times.idle, result["sys.cpu.idle"])
self.assertEqual(cpu_times.iowait, result["sys.cpu.iowait"])
self.assertEqual(cpu_times.irq, result["sys.cpu.irq"])
elif sys.platform.lower().startswith("win32"):
self.assertEqual(cpu_times.user, result["sys.cpu.user"])
self.assertEqual(cpu_times.system, result["sys.cpu.system"])
self.assertEqual(cpu_times.idle, result["sys.cpu.idle"])
elif sys.platform.lower().startswith("darwin"):
self.assertEqual(cpu_times.user, result["sys.cpu.user"])
self.assertEqual(cpu_times.system, result["sys.cpu.system"])
self.assertEqual(cpu_times.idle, result["sys.cpu.idle"])
self.assertEqual(cpu_times.nice, result["sys.cpu.nice"])
elif sys.platform.lower().startswith("freebsd"):
self.assertEqual(cpu_times.user, result["sys.cpu.user"])
self.assertEqual(cpu_times.system, result["sys.cpu.system"])
self.assertEqual(cpu_times.idle, result["sys.cpu.idle"])
self.assertEqual(cpu_times.irq, result["sys.cpu.irq"])
0
Example 30
Project: txstatsd Source File: test_process.py
def test_per_cpu_counters(self):
"""System percpu counters are collected through psutil."""
cpu_times = psutil.cpu_times()
with mock.patch("psutil.cpu_times"):
psutil.cpu_times.return_value = [cpu_times, cpu_times]
result = report_system_stats(percpu=True)
psutil.cpu_times.assert_called_once_with(percpu=True)
# cpu_times is platform-dependent
if sys.platform.lower().startswith("linux"):
self.assertEqual(cpu_times.user, result["sys.cpu.000.user"])
self.assertEqual(cpu_times.system, result["sys.cpu.000.system"])
self.assertEqual(cpu_times.idle, result["sys.cpu.000.idle"])
self.assertEqual(cpu_times.iowait, result["sys.cpu.000.iowait"])
self.assertEqual(cpu_times.irq, result["sys.cpu.001.irq"])
self.assertEqual(cpu_times.user, result["sys.cpu.001.user"])
self.assertEqual(cpu_times.system, result["sys.cpu.001.system"])
self.assertEqual(cpu_times.idle, result["sys.cpu.001.idle"])
self.assertEqual(cpu_times.iowait, result["sys.cpu.001.iowait"])
self.assertEqual(cpu_times.irq, result["sys.cpu.001.irq"])
elif sys.platform.lower().startswith("win32"):
self.assertEqual(cpu_times.user, result["sys.cpu.000.user"])
self.assertEqual(cpu_times.system, result["sys.cpu.000.system"])
self.assertEqual(cpu_times.idle, result["sys.cpu.000.idle"])
self.assertEqual(cpu_times.user, result["sys.cpu.001.user"])
self.assertEqual(cpu_times.system, result["sys.cpu.001.system"])
self.assertEqual(cpu_times.idle, result["sys.cpu.001.idle"])
elif sys.platform.lower().startswith("darwin"):
self.assertEqual(cpu_times.user, result["sys.cpu.000.user"])
self.assertEqual(cpu_times.system, result["sys.cpu.000.system"])
self.assertEqual(cpu_times.idle, result["sys.cpu.000.idle"])
self.assertEqual(cpu_times.nice, result["sys.cpu.000.nice"])
self.assertEqual(cpu_times.user, result["sys.cpu.001.user"])
self.assertEqual(cpu_times.system, result["sys.cpu.001.system"])
self.assertEqual(cpu_times.idle, result["sys.cpu.001.idle"])
self.assertEqual(cpu_times.nice, result["sys.cpu.001.nice"])
elif sys.platform.lower().startswith("freebsd"):
self.assertEqual(cpu_times.user, result["sys.cpu.000.user"])
self.assertEqual(cpu_times.system, result["sys.cpu.000.system"])
self.assertEqual(cpu_times.idle, result["sys.cpu.000.idle"])
self.assertEqual(cpu_times.irq, result["sys.cpu.000.irq"])
self.assertEqual(cpu_times.user, result["sys.cpu.001.user"])
self.assertEqual(cpu_times.system, result["sys.cpu.001.system"])
self.assertEqual(cpu_times.idle, result["sys.cpu.001.idle"])
self.assertEqual(cpu_times.irq, result["sys.cpu.001.irq"])
0
Example 31
def is_jython():
return sys.platform.lower().startswith('java')
0
Example 32
Project: abjad Source File: IOManager.py
@staticmethod
def open_file(file_path, application=None, line_number=None):
r'''Opens `file_path`.
Uses `application` when `application` is not none.
Uses Abjad configuration file `text_editor` when
`application` is none.
Takes best guess at operating system-specific file opener when both
`application` and Abjad configuration file `text_editor` are none.
Respects `line_number` when `file_path` can be opened with text editor.
Returns none.
'''
from abjad import abjad_configuration
if sys.platform.lower().startswith('win'):
os.startfile(file_path)
return
viewer = None
if sys.platform.lower().startswith('linux'):
viewer = application or 'xdg-open'
elif file_path.endswith('.pdf'):
viewer = application or abjad_configuration['pdf_viewer']
elif file_path.endswith((
'.log',
'.py',
'.rst',
'.txt',
)):
viewer = application or abjad_configuration['text_editor']
elif file_path.endswith((
'.mid',
'.midi',
)):
viewer = application or abjad_configuration['midi_player']
viewer = viewer or 'open'
if line_number:
command = '{} +{} {}'.format(viewer, line_number, file_path)
else:
command = '{} {}'.format(viewer, file_path)
IOManager.spawn_subprocess(command)
0
Example 33
def hack_distutils(debug=False, fast_link=True, what_opt=3):
# hack distutils.sysconfig to eliminate debug flags
# stolen from mpi4py
def remove_prefixes(optlist, bad_prefixes):
for bad_prefix in bad_prefixes:
for i, flag in enumerate(optlist):
if flag.startswith(bad_prefix):
optlist.pop(i)
break
return optlist
import sys
if not sys.platform.lower().startswith("win"):
from distutils import sysconfig
cvars = sysconfig.get_config_vars()
cflags = cvars.get('OPT')
if cflags:
cflags = remove_prefixes(cflags.split(),
['-g', '-O', '-Wstrict-prototypes', '-DNDEBUG'])
if debug:
cflags.append("-g")
else:
if what_opt is None:
pass
else:
cflags.append("-O%s" % what_opt)
cflags.append("-DNDEBUG")
cvars['OPT'] = str.join(' ', cflags)
cvars["CFLAGS"] = cvars["BASECFLAGS"] + " " + cvars["OPT"]
if fast_link:
for varname in ["LDSHARED", "BLDSHARED"]:
ldsharedflags = cvars.get(varname)
if ldsharedflags:
ldsharedflags = remove_prefixes(ldsharedflags.split(),
['-Wl,-O'])
cvars[varname] = str.join(' ', ldsharedflags)
0
Example 34
def consoleprint(s):
if sys.platform.lower().startswith('win'):
print(s, '\r', end='')
else:
print(s)
0
Example 35
def get_multiarch():
"""This function returns the suffix for lib directories on supported
systems or an empty string it uses two step approach to look for multiarch:
first run gcc -print-multiarch and if failed try to run
dpkg-architecture."""
if not sys.platform.lower().startswith('linux'):
return ''
error_thrown = False
try:
p = subprocess.Popen(
['gcc', '-print-multiarch'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
except (OSError, FileNotFoundError):
error_thrown = True
if error_thrown or p.returncode != 0:
try:
out, err = subprocess.Popen(
['dpkg-architecture', '-qDEB_HOST_MULTIARCH'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
except (OSError, FileNotFoundError):
return ''
# be sure to return empty string or a valid multiarch tuple
decoded = out.decode().strip()
assert(not decoded or decoded.count('-') == 2)
return decoded
0
Example 36
def hack_distutils(debug=False, fast_link=True):
# hack distutils.sysconfig to eliminate debug flags
# stolen from mpi4py
def remove_prefixes(optlist, bad_prefixes):
for bad_prefix in bad_prefixes:
for i, flag in enumerate(optlist):
if flag.startswith(bad_prefix):
optlist.pop(i)
break
return optlist
import sys
if not sys.platform.lower().startswith("win"):
from distutils import sysconfig
cvars = sysconfig.get_config_vars()
cflags = cvars.get('OPT')
if cflags:
cflags = remove_prefixes(cflags.split(),
['-g', '-O', '-Wstrict-prototypes', '-DNDEBUG'])
if debug:
cflags.append("-g")
else:
cflags.append("-O3")
cflags.append("-DNDEBUG")
cvars['OPT'] = str.join(' ', cflags)
cvars["CFLAGS"] = cvars["BASECFLAGS"] + " " + cvars["OPT"]
if fast_link:
for varname in ["LDSHARED", "BLDSHARED"]:
ldsharedflags = cvars.get(varname)
if ldsharedflags:
ldsharedflags = remove_prefixes(ldsharedflags.split(),
['-Wl,-O'])
cvars[varname] = str.join(' ', ldsharedflags)
0
Example 37
def _gen_makefile():
if sys.platform.lower().startswith("win"):
f = open(os.path.join(out_dir, "make.bat"), "w")
print >> f, "@set GOPATH=%s" % out_dir
print >> f, "go build -o %s.exe src/lar_prog_%s/lar_prog.%s.go" % (main_module_name, main_module_name, main_module_name)
print >> f, "@if %ERRORLEVEL% == 0 goto success"
print >> f, "@pause"
print >> f, ":success"
f = open(os.path.join(out_dir, "make_and_run.bat"), "w")
print >> f, "@set GOPATH=%s" % out_dir
print >> f, "go build -o %s.exe src/lar_prog_%s/lar_prog.%s.go" % (main_module_name, main_module_name, main_module_name)
print >> f, "@if %ERRORLEVEL% == 0 goto success"
print >> f, "@pause"
print >> f, "@exit"
print >> f, ":success"
print >> f, "%s.exe" % main_module_name
print >> f, "@pause"
print >> f, "@exit"
else:
raise Exception("Not implemented on '%s'" % sys.platform)
0
Example 38
Project: nupic Source File: network_test.py
@unittest.skipIf(sys.platform.lower().startswith("win"),
"Not supported on Windows, yet!")
def testErrorHandling(self):
n = engine.Network()
# Test trying to add non-existent node
with self.assertRaises(Exception) as cm:
n.addRegion('r', 'py.NonExistingNode', '')
self.assertEqual(cm.exception.message, "Matching Python module for NonExistingNode not found.")
orig_import = __import__
def import_mock(name, *args):
if name == "nupic.regions.UnimportableNode":
raise SyntaxError("invalid syntax (UnimportableNode.py, line 5)")
return orig_import(name, *args)
with patch('__builtin__.__import__', side_effect=import_mock):
# Test failure during import
with self.assertRaises(Exception) as cm:
n.addRegion('r', 'py.UnimportableNode', '')
self.assertEqual(cm.exception.message, "invalid syntax (UnimportableNode.py, line 5)")
# Test failure in the __init__() method
with self.assertRaises(Exception) as cm:
n.addRegion('r', 'py.TestNode', '{ failInInit: 1 }')
self.assertEqual(cm.exception.message, "TestNode.__init__() Failing on purpose as requested")
# Test failure inside the compute() method
with self.assertRaises(Exception) as cm:
r = n.addRegion('r', 'py.TestNode', '{ failInCompute: 1 }')
r.dimensions = engine.Dimensions([4, 4])
n.initialize()
n.run(1)
self.assertEqual(str(cm.exception),
'TestNode.compute() Failing on purpose as requested')
# Test failure in the static getSpec
from nupic.bindings.regions.TestNode import TestNode
TestNode._failIngetSpec = True
with self.assertRaises(Exception) as cm:
TestNode.getSpec()
self.assertEqual(str(cm.exception),
'Failing in TestNode.getSpec() as requested')
del TestNode._failIngetSpec
0
Example 39
Project: nupic Source File: network_test.py
@unittest.skipIf(sys.platform.lower().startswith("win"),
"Not supported on Windows, yet!")
def testTwoRegionNetwork(self):
n = engine.Network()
region1 = n.addRegion("region1", "TestNode", "")
region2 = n.addRegion("region2", "TestNode", "")
names = []
for name in n.regions:
names.append(name)
self.assertEqual(names, ['region1', 'region2'])
print n.getPhases('region1')
self.assertEqual(n.getPhases('region1'), (0,))
self.assertEqual(n.getPhases('region2'), (1,))
n.link("region1", "region2", "TestFanIn2", "")
print "Initialize should fail..."
with self.assertRaises(Exception):
n.initialize()
print "Setting region1 dims"
r1dims = engine.Dimensions([6, 4])
region1.setDimensions(r1dims)
print "Initialize should now succeed"
n.initialize()
r2dims = region2.dimensions
self.assertEqual(len(r2dims), 2)
self.assertEqual(r2dims[0], 3)
self.assertEqual(r2dims[1], 2)
# Negative test
with self.assertRaises(Exception):
region2.setDimensions(r1dims)
0
Example 40
Project: nupic Source File: network_test.py
@unittest.skipIf(sys.platform.lower().startswith("win"),
"Not supported on Windows, yet!")
def testPyNodeGetSetParameter(self):
n = engine.Network()
r = n.addRegion("region", "py.TestNode", "")
print "Setting region1 dims"
r.dimensions = engine.Dimensions([6, 4])
print "Initialize should now succeed"
n.initialize()
result = r.getParameterReal64('real64Param')
self.assertEqual(result, 64.1)
r.setParameterReal64('real64Param', 77.7)
result = r.getParameterReal64('real64Param')
self.assertEqual(result, 77.7)
0
Example 41
Project: nupic Source File: network_test.py
@unittest.skipIf(sys.platform.lower().startswith("win"),
"Not supported on Windows, yet!")
def testPyNodeGetNodeSpec(self):
n = engine.Network()
r = n.addRegion("region", "py.TestNode", "")
print "Setting region1 dims"
r.setDimensions(engine.Dimensions([6, 4]))
print "Initialize should now succeed"
n.initialize()
ns = r.spec
self.assertEqual(len(ns.inputs), 1)
i = ns.inputs['bottomUpIn']
self.assertEqual(i.description, 'Primary input for the node')
self.assertEqual(len(ns.outputs), 1)
i = ns.outputs['bottomUpOut']
self.assertEqual(i.description, 'Primary output for the node')
0
Example 42
Project: nupic Source File: network_test.py
@unittest.skipIf(sys.platform.lower().startswith("win"),
"Not supported on Windows, yet!")
def testTwoRegionPyNodeNetwork(self):
n = engine.Network()
region1 = n.addRegion("region1", "py.TestNode", "")
region2 = n.addRegion("region2", "py.TestNode", "")
n.link("region1", "region2", "TestFanIn2", "")
print "Initialize should fail..."
with self.assertRaises(Exception):
n.initialize()
print "Setting region1 dims"
r1dims = engine.Dimensions([6, 4])
region1.setDimensions(r1dims)
print "Initialize should now succeed"
n.initialize()
r2dims = region2.dimensions
self.assertEqual(len(r2dims), 2)
self.assertEqual(r2dims[0], 3)
self.assertEqual(r2dims[1], 2)
0
Example 43
def _dump_content(self, response, description):
"""Dump the html content in a file.
Use firefox to render the content if we are in rt viewing mode."""
dump_dir = self._dump_dir
if dump_dir is None:
return
if getattr(response, 'code', 301) in [301, 302, 303, 307]:
return
if not response.body:
return
if not os.access(dump_dir, os.W_OK):
os.mkdir(dump_dir, 0o775)
content_type = response.headers.get('content-type')
if content_type == 'text/xml':
ext = '.xml'
else:
ext = os.path.splitext(response.url)[1]
if not ext.startswith('.') or len(ext) > 4:
ext = '.html'
file_path = os.path.abspath(
os.path.join(dump_dir, '%3.3i%s' % (self.steps, ext)))
f = open(file_path, 'w')
f.write(response.body)
f.close()
if self._viewing:
cmd = 'firefox -remote "openfile(file://%s#%s,new-tab)"' % (
file_path, description)
ret = os.system(cmd)
if ret != 0 and not sys.platform.lower().startswith('win'):
self.logi('Failed to remote control firefox: %s' % cmd)
self._viewing = False
0
Example 44
def get_null_file():
if sys.platform.lower().startswith('win'):
return "NUL"
else:
return "/dev/null"
0
Example 45
def parseArgs(self, argv):
"""Parse programs args."""
global g_doctest_verbose
parser = OptionParser(self.USAGE, formatter=TitledHelpFormatter(),
version="FunkLoad %s" % get_version())
parser.add_option("", "--config", type="string", dest="config", metavar='CONFIG',
help="Path to alternative config file.")
parser.add_option("-q", "--quiet", action="store_true",
help="Minimal output.")
parser.add_option("-v", "--verbose", action="store_true",
help="Verbose output.")
parser.add_option("-d", "--debug", action="store_true",
help="FunkLoad and doctest debug output.")
parser.add_option("--debug-level", type="int",
help="Debug level 3 is more verbose.")
parser.add_option("-u", "--url", type="string", dest="main_url",
help="Base URL to bench without ending '/'.")
parser.add_option("-m", "--sleep-time-min", type="string",
dest="ftest_sleep_time_min",
help="Minumum sleep time between request.")
parser.add_option("-M", "--sleep-time-max", type="string",
dest="ftest_sleep_time_max",
help="Maximum sleep time between request.")
parser.add_option("--dump-directory", type="string",
dest="dump_dir",
help="Directory to dump html pages.")
parser.add_option("-V", "--firefox-view", action="store_true",
help="Real time view using firefox, "
"you must have a running instance of firefox "
"in the same host.")
parser.add_option("--no-color", action="store_true",
help="Monochrome output.")
parser.add_option("-l", "--loop-on-pages", type="string",
dest="loop_steps",
help="Loop as fast as possible without concurrency "
"on pages, expect a page number or a slice like 3:5."
" Output some statistics.")
parser.add_option("-n", "--loop-number", type="int",
dest="loop_number", default=10,
help="Number of loop.")
parser.add_option("--accept-invalid-links", action="store_true",
help="Do not fail if css/image links are "
"not reachable.")
parser.add_option("--simple-fetch", action="store_true",
dest="ftest_simple_fetch",
help="Don't load additional links like css "
"or images when fetching an html page.")
parser.add_option("--stop-on-fail", action="store_true",
help="Stop tests on first failure or error.")
parser.add_option("-e", "--regex", type="string", default=None,
help="The test names must match the regex.")
parser.add_option("--list", action="store_true",
help="Just list the test names.")
parser.add_option("--doctest", action="store_true", default=False,
help="Check for a doc test.")
parser.add_option("--pause", action="store_true",
help="Pause between request, "
"press ENTER to continue.")
parser.add_option("--profile", action="store_true",
help="Run test under the Python profiler.")
options, args = parser.parse_args()
if self.module is None:
if len(args) == 0:
parser.error("incorrect number of arguments")
# remove the .py
module = args[0]
if module.endswith('.py'):
module = os.path.basename(os.path.splitext(args[0])[0])
self.module = module
else:
args.insert(0, self.module)
if not options.doctest:
global g_has_doctest
g_has_doctest = False
if options.verbose:
self.verbosity = 2
if options.quiet:
self.verbosity = 0
g_doctest_verbose = False
if options.debug or options.debug_level:
options.ftest_debug_level = 1
options.ftest_log_to = 'console file'
g_doctest_verbose = True
if options.debug_level:
options.ftest_debug_level = int(options.debug_level)
if sys.platform.lower().startswith('win'):
self.color = False
else:
self.color = not options.no_color
self.test_name_pattern = options.regex
self.list_tests = options.list
self.profile = options.profile
# set testloader options
self.testLoader.options = options
if self.defaultTest is not None:
self.testNames = [self.defaultTest]
elif len(args) > 1:
self.testNames = args[1:]
0
Example 46
Project: FunkLoad Source File: test_Install.py
def test_01_requires(self):
try:
import webunit
except ImportError:
self.fail('Missing Required module webunit')
try:
import funkload
except ImportError:
self.fail('Unable to import funkload module.')
try:
import docutils
except ImportError:
print ("WARNING: missing docutils module, "
"no HTML report available.")
if sys.platform.lower().startswith('win'):
ret = winplatform_getstatusoutput('wgnuplot --version')
if not ret:
self.fail('Cannot run self.system on windows without the subprocess module (python 2.6)')
else:
ret = commands.getstatusoutput('gnuplot --version')
print(ret[1])
if ret[0]:
print ("WARNING: gnuplot is missing, no charts available in "
"HTML reports.")
from funkload.TestRunner import g_has_doctest
if not g_has_doctest:
print("WARNING: Python 2.4 is required to support doctest")