示例#1
0
 def __init__(self, id):
    print("In init method with " +str(id) +"\n")
    self.id = id
    self.k_sem_lock = sysv_ipc.ftok("/sketch/k_lock.txt", self.id, True)
    self.k_shm = sysv_ipc.ftok("/sketch/k_shm.txt", self.id, True)
    self.k_sem_data = sysv_ipc.ftok("/sketch/k_data.txt", self.id, True)
    self.k_sem_space = sysv_ipc.ftok("/sketch/k_space.txt", self.id, True)
示例#2
0
	def __init__(self, id):
		print("IPC monitor created for id: " + str(id) + "\n")
		self.id = id
		self.k_sem_lock = sysv_ipc.ftok("/sketch/k_lock.txt", self.id, True)
		self.k_shm = sysv_ipc.ftok("/sketch/k_shm.txt", self.id, True)
		self.k_sem_data = sysv_ipc.ftok("/sketch/k_data.txt", self.id, True)
		self.k_sem_space = sysv_ipc.ftok("/sketch/k_space.txt", self.id, True)
示例#3
0
 def test_ftok_raises_os_error(self):
     """Ensure ftok() failure raises an exception"""
     with tempfile.TemporaryDirectory() as tmp_dir_name:
         # Create a path that should cause ftok() to fail.
         does_not_exist_path = os.path.join(tmp_dir_name, "does_not_exist")
         with self.assertRaises(OSError):
             sysv_ipc.ftok(does_not_exist_path, 42, silence_warning=True)
示例#4
0
    def _run(self):
        # Obtain the keys for the shared memory and semaphores.
        keySharedMemory = sysv_ipc.ftok(self.name, 1, True)
        keySemMutex = sysv_ipc.ftok(self.name, 2, True)
        keySemCondition = sysv_ipc.ftok(self.name, 3, True)

        # Instantiate the SharedMemory and Semaphore objects.
        shm = sysv_ipc.SharedMemory(keySharedMemory)
        mutex = sysv_ipc.Semaphore(keySemCondition)
        cond = sysv_ipc.Semaphore(keySemCondition)

        while self.running:
            start = time.time()

            try:
                cond.Z(timeout=1)
            except:
                continue

            # with statement???
            mutex.acquire()
            shm.attach()
            buf = shm.read()
            shm.detach()
            mutex.release()

            img = numpy.frombuffer(buf, numpy.uint8).reshape(480, 640, 4)
            self.on_data(img)

            elapsed_time = time.time() - start
            logger.info('%2.2f Hz', 1.0 / elapsed_time)
    def test_ftok(self):
        """Exercise ftok()"""
        with warnings.catch_warnings(record=True) as recorded_warnings:
            warnings.simplefilter("always")

            sysv_ipc.ftok('.', 42)

            self.assertEqual(len(recorded_warnings), 1)
            self.assertTrue(issubclass(recorded_warnings[-1].category, Warning))

        with warnings.catch_warnings(record=True) as recorded_warnings:
            warnings.simplefilter("always")

            sysv_ipc.ftok('.', 42, silence_warning=True)

            self.assertEqual(len(recorded_warnings), 0)
示例#6
0
def main():
    HEADER_SHM = 'i'
    HEADER_PROCESS_STATUS = '32s32siiii32s128s'

    key = sysv_ipc.ftok(SHM_PATH, ord(FTOK_ID), True)
    Shm = sysv_ipc.SharedMemory(key)

    UnpackShmStrSize = struct.calcsize(HEADER_SHM)
    UnpackProcStrSize = struct.calcsize(HEADER_PROCESS_STATUS)
    TotalUnpackSize = UnpackShmStrSize + UnpackProcStrSize * MAX_EXT_SERVER

    ShmValue = ReadBytes(Shm, TotalUnpackSize)

    ProcessStatusTpl = namedtuple('ProcessStatusTpl', ATTR_EXT_STATUS)
    print '====== Process List ===================================================='
    print ' idx | vld | pid    | ppid   | name             | alias                |'
    print '------------------------------------------------------------------------'
    offset = 0
    for i in range(MAX_EXT_SERVER):
        offset = UnpackShmStrSize + UnpackProcStrSize * i
        ProcessStatus = ProcessStatusTpl._make(
            struct.unpack_from(HEADER_PROCESS_STATUS, ShmValue, offset))
        ShmProcStatusDisplayFmt = ' %s | %s' % (RemoveNul(
            ProcessStatus.szName), RemoveNul(ProcessStatus.szProcName))
        print ShmProcStatusDisplayFmt
#		print ProcessStatus
    print '------------------------------------------------------------------------'
示例#7
0
def main():
    HEADER_SHM = 'IhhI'
    HEADER_PROCESS_STATUS = 'iiii%ds%dsi%ds%ds' % (
        MAX_PROCESS_NAME_LEN, MAX_PROCESS_NAME_LEN,
        (MAX_NUM_OF_ARGVS * MAX_ARGV_LEN + MAX_NUM_OF_ARGVS * 4),
        4 * MAX_ALARM_COUNT)

    key = sysv_ipc.ftok(SHM_PATH, ord(FTOK_ID), True)
    Shm = sysv_ipc.SharedMemory(key)

    UnpackShmStrSize = struct.calcsize(HEADER_SHM)
    UnpackProcStrSize = struct.calcsize(HEADER_PROCESS_STATUS)
    TotalUnpackSize = UnpackShmStrSize + UnpackProcStrSize * MAX_PROCESSES

    ShmValue = ReadBytes(Shm, TotalUnpackSize)

    ProcessStatusTpl = namedtuple('ProcessStatusTpl', ATTR_PROCESS_STATUS)
    print '====== Process List ===================================================='
    print ' idx | vld | pid    | ppid   | name             | alias                |'
    print '------------------------------------------------------------------------'
    offset = 0
    for i in range(MAX_PROCESSES):
        offset = UnpackShmStrSize + UnpackProcStrSize * i
        ProcessStatus = ProcessStatusTpl._make(
            struct.unpack_from(HEADER_PROCESS_STATUS, ShmValue, offset))
        ShmProcStatusDisplayFmt = ' %3s | %3s | %6s | %6s | %-16s | %-20s |' % (
            i, ProcessStatus.valid, ProcessStatus.pid, ProcessStatus.ppid,
            RemoveNul(ProcessStatus.szName), RemoveNul(ProcessStatus.szAlias))
        print ShmProcStatusDisplayFmt
    print '------------------------------------------------------------------------'
示例#8
0
def main():
    # Create shared memory file
    dir = os.getcwd()
    file = "shm"
    shmfile = os.path.join(dir, file)
    f = open(shmfile, "w+")
    f.close()

    # Attach shared memory to process
    key = sysv_ipc.ftok(shmfile, 255)
    shm = sysv_ipc.SharedMemory(key, sysv_ipc.IPC_CREAT, size=256)

    # Interval Timer
    interval = Interval(0.001, CoordinateToShm, args=[shm])  #run every ms
    print("shmfile: {}".format(shmfile))
    print("Starting Interval, press CTRL+C to stop.")
    interval.start()

    while True:
        try:
            time.sleep(0.1)
        except KeyboardInterrupt:
            print("Shutting down")
            interval.stop()
            shm.detach()
            shm.remove()
            break
示例#9
0
    def queue_key():
        filepath = sys.argv[1]
        key = sysv_ipc.ftok(filepath, id=42, silence_warning = True)
        result = hex(int(key))
        print 'key:', result

        command = 'ipcs -q | grep %s' % ( result, )
        os.system( command )
示例#10
0
 def _GetShmId(self):
     key = sysv_ipc.ftok(BRBT_MPRM_SHM_PATH, ord(FTOK_ID), True)
     try:
         Shm = sysv_ipc.SharedMemory(key)
     except Exception as e:
         self.error = e
         raise (NameError, "Shared Memory read failed!!")
     else:
         return Shm
示例#11
0
    def __init__(self, master):
        self.config = master.config
        try:
            self.configConfig = master.config["config"]
        except KeyError:
            self.configConfig = {}
        self.debugLevel = self.configConfig.get("debugLevel", 0)
        self.master = master

        try:
            self.configIPC = master.config["control"]["IPC"]
        except KeyError:
            self.configIPC = {}
        self.status = self.configIPC.get("enabled", False)

        # Unload if this module is disabled or misconfigured
        if not self.status:
            self.master.releaseModule("lib.TWCManager.Control",
                                      "WebIPCControl")
            return None

        # Create an IPC (Interprocess Communication) message queue that we can
        # periodically check to respond to queries from the TWCManager web interface.
        #
        # These messages will contain commands like "start charging at 10A" or may ask
        # for information like "how many amps is the solar array putting out".
        #
        # The message queue is identified by a numeric key. This script and the web
        # interface must both use the same key. The "ftok" function facilitates creating
        # such a key based on a shared piece of information that is not likely to
        # conflict with keys chosen by any other process in the system.
        #
        # ftok reads the inode number of the file or directory pointed to by its first
        # parameter. This file or dir must already exist and the permissions on it don't
        # seem to matter. The inode of a particular file or dir is fairly unique but
        # doesn't change often so it makes a decent choice for a key.  We use the parent
        # directory of the TWCManager script.
        #
        # The second parameter to ftok is a single byte that adds some additional
        # uniqueness and lets you create multiple queues linked to the file or dir in
        # the first param. We use 'T' for Tesla.
        #
        # If you can't get this to work, you can also set key = <some arbitrary number>
        # and in the web interface, use the same arbitrary number. While that could
        # conflict with another process, it's very unlikely to.
        self.webIPCkey = sysv_ipc.ftok(self.config["config"]["settingsPath"],
                                       ord("T"), True)

        # Use the key to create a message queue with read/write access for all users.
        self.webIPCqueue = sysv_ipc.MessageQueue(self.webIPCkey,
                                                 sysv_ipc.IPC_CREAT, 0o666)
        if self.webIPCqueue == None:
            self.master.debugLog(
                1,
                "WebIPCCtrl",
                "ERROR: Can't create Interprocess Communication message queue to communicate with web interface.",
            )
示例#12
0
def connectShm():

    warnings.simplefilter("ignore")
    path = "/tmp"
    projectID = 2338
    key = ipc.ftok(path, projectID)
    shm = ipc.SharedMemory(key, 0, 0)
    shm.attach(0, 0)

    return shm
示例#13
0
def main():
    path = "/tmp"
    key = ipc.ftok(path, 2333)
    shm = ipc.SharedMemory(key, 0, 0)
    #I found if we do not attach ourselves
    #it will attach as ReadOnly.
    shm.attach(0, 0)
    buf = shm.read(19)
    print(buf)
    shm.detach()
    pass
示例#14
0
def main():
    path = "/tmp"
    key = ipc.ftok(path, 2333)
    shm = ipc.SharedMemory(key, ipc.IPC_CREAT, 0600, 1024)  
    shm.write("12343 t2", 0)
    shm.write("01010101", 8)
    buf = shm.read(8, 0)
    print("Text: " + buf);
    print("LEDS: " + shm.read(8, 8))
    print("Buttons: " + shm.read(8, 16))
    shm.detach()
    pass
示例#15
0
    def test_ftok(self):
        """Exercise ftok()'s behavior of raising a warning as documented"""
        # Test default value of silence_warning
        with warnings.catch_warnings(record=True) as recorded_warnings:
            warnings.simplefilter("always")

            sysv_ipc.ftok('.', 42)

            self.assertEqual(len(recorded_warnings), 1)
            self.assertTrue(issubclass(recorded_warnings[-1].category,
                                       Warning))

        # Test explicit False value of silence_warning
        with warnings.catch_warnings(record=True) as recorded_warnings:
            warnings.simplefilter("always")

            sysv_ipc.ftok('.', 42, silence_warning=False)

            self.assertEqual(len(recorded_warnings), 1)
            self.assertTrue(issubclass(recorded_warnings[-1].category,
                                       Warning))

        # Test explicit True value of silence_warning
        with warnings.catch_warnings(record=True) as recorded_warnings:
            warnings.simplefilter("always")

            sysv_ipc.ftok('.', 42, silence_warning=True)

            self.assertEqual(len(recorded_warnings), 0)
示例#16
0
def main():
    path = "./"
    key = ipc.ftok(path, 2333)
    shm = ipc.SharedMemory(key, 0, 0)

    # I found if we do not attach ourselves
    # it will attach as ReadOnly.
    shm.attach(0, 0)
    buf = shm.read(
        0, 0
    )  # If byte_count is zero (the default) the entire buffer is returned.
    print(buf)
    shm.detach()
    pass
示例#17
0
    def ReadExtShm(self, HaStatus):
        if HaStatus == 'STANDBY':
            print " This system is Standby side "
            print " Remote connection Information is available in SPS active side "
            return 'OK'

        HEADER_EXT_SHM = 'i'
        HEADER_EXT_SERVER_STATUS = '32s32siiii32s128s'

        key = sysv_ipc.ftok(VMS_SHM_FTOK_PATH_EXT, ord(FTOK_ID), True)
        Shm = sysv_ipc.SharedMemory(key)

        UnpackExtShmStrSize = struct.calcsize(HEADER_EXT_SHM)
        UnpackExtServerStrSize = struct.calcsize(HEADER_EXT_SERVER_STATUS)
        TotalUnpackSize = UnpackExtShmStrSize + UnpackExtServerStrSize * MAX_EXT_SERVER

        ShmValue = self.ReadBytes(Shm, TotalUnpackSize)

        ExtServerStatusTpl = namedtuple('ExtServerStatusTpl',
                                        ATTR_EXT_SERVER_STATUS)
        print '====== External Server List ============================================'
        print ' name         | procname        | ip              | port  | ExtStatus'
        print '------------------------------------------------------------------------'
        offset = 0
        for i in range(MAX_EXT_SERVER):
            offset = UnpackExtShmStrSize + UnpackExtServerStrSize * i
            ExtServerStatus = ExtServerStatusTpl._make(
                struct.unpack_from(HEADER_EXT_SERVER_STATUS, ShmValue, offset))
            if ExtServerStatus.nValid:
                #				print '====' + ExtServerStatus.szName
                if self.RemoveNul(ExtServerStatus.szName) == 'VVMG':
                    continue

                if ExtServerStatus.nStatus:
                    ExtStatus = 'Connected'
                else:
                    ExtStatus = 'DisConnected'
                    self.result = 'NOK'

                ShmExtServerStatusDisplayFmt = ' %-12s | %-15s | %-15s | %5s | %12s' % (
                    self.RemoveNul(ExtServerStatus.szName),
                    self.RemoveNul(ExtServerStatus.szProcName),
                    self.RemoveNul(ExtServerStatus.szIp),
                    ExtServerStatus.nPort, ExtStatus)

                print ShmExtServerStatusDisplayFmt
        print '------------------------------------------------------------------------'

        return self.result
示例#18
0
 def Connect(self, shmFile):
     try:
         if (shmFile == None):
             msg = "Status: FD Not Chosen, Can't Connect"
             self.SetConnectionState(False)
         else:
             self._shmFile = shmFile
             self._shmKey = sysv_ipc.ftok(self._shmFile, 255)
             self._shm = sysv_ipc.SharedMemory(self._shmKey)
             self.SetConnectionState(True)
             msg = "Status: Shared Memory Connected"
     except Exception as err:
             msg = "Error: {}".format(err)
             self.SetConnectionState(False)
     finally:
         self.SupplyStatusMessage.emit(msg)
def main():
    filepath = '/home/tannerbitz/Documents/shmfile'

    key = sysv_ipc.ftok(filepath, 255)
    # Open shared memory.
    #   - flags=0 attempts to open an existing shared memory segment
    #   - mode
    shm = sysv_ipc.SharedMemory(key)

    int_bytestr = shm.read(4);

    nFloats = int.from_bytes(int_bytestr, byteorder='little', signed=False)

    float_bytestr = shm.read(nFloats*4, offset=4)

    we_all_float_on = np.frombuffer(float_bytestr, dtype=np.single)
    print(we_all_float_on)
示例#20
0
文件: _aws_som.py 项目: Accelize/drm
    def _init_fpga(self):
        """
        Initialize FPGA handle with driver library.
        """
        '''
        # Find all devices
        xcl_probe = self._fpga_library.xclProbe
        xcl_probe.restype = _c_uint  # Devices count

        if xcl_probe() < 1:
            raise RuntimeError("xclProbe does not found devices")

        # Open device
        xcl_open = self._fpga_library.xclOpen
        xcl_open.restype = _POINTER(_c_void_p)  # Device handle
        xcl_open.argtypes = (
            _c_uint,  # deviceIndex
            _c_char_p,  # logFileName
            _c_int,  # level
        )
        log_file = _join(self._log_dir, 'slot_%d_xrt.log' % self._fpga_slot_id)
        device_handle = xcl_open(
            self._fpga_slot_id,
            log_file.encode(),
            3  # XCL_ERROR
        )
        if not device_handle:
            raise RuntimeError("xclOpen failed to open device")
        self._fpga_handle = device_handle
        '''
        # Connect to Shared Memory
        self.shm_pages = list()
        for i in range(1, 7):
            key = ipc.ftok(SHM_PATH, i)
            shm = ipc.SharedMemory(key, 0, 0)
            shm.attach(0, 0)
            self.shm_pages.append(shm)
        print('Connected to Shared Memory')
示例#21
0
    def run(self):
        # Configure IPC
        path = "/tmp"
        text = ""
        leds = 0
        buttons = 0
        try:
            key = ipc.ftok(path, 2333)
            shm = ipc.SharedMemory(key, ipc.IPC_CREAT, 0600, 1024)
        except:
            print("Error")

        # Init board
        board = self.initialize()
        while True:
            # Text
            textBuf = shm.read(8, 0)
            if text != textBuf:
                text = textBuf
                board.set_text(text)

            # LEDS
            ledsBuf = shm.read(8, 8)
            if leds != ledsBuf:
                leds = ledsBuf
                for i in range(0, 8):
                    if leds[i] == "1":
                        board.set_led(i, 255)
                    else:
                        board.set_led(i, 0)

            # Buttons
            buttonsBuf = board.get_buttons()
            if buttonsBuf != buttons:
                buttons = buttonsBuf
                shm.write('{0:08b}'.format(buttons), 16)
示例#22
0
def get_sem_id() -> int:
    sysv_id = sysv_ipc.ftok(__file__, 1, silence_warning=True)
    debug(f"ftok() returned this ID: {sysv_id}")
    return sysv_id
 def test_ftok_kwargs(self):
     """Ensure ftok() takes kwargs as advertised"""
     sysv_ipc.ftok('.', 42, silence_warning=True)
示例#24
0
# Register a handler for a message; the following example is listening
# for messageID 1039 which represents opendlv.proxy.DistanceReading.
# Cf. here: https://github.com/chalmers-revere/opendlv.standard-message-set/blob/master/opendlv.odvd#L113-L115
messageIDDistanceReading = 1039
session.registerMessageCallback(
    messageIDDistanceReading, onDistance,
    opendlv_standard_message_set_v0_9_6_pb2.opendlv_proxy_DistanceReading)
# Connect to the network session.
session.connect()

################################################################################
# The following lines connect to the camera frame that resides in shared memory.
# This name must match with the name used in the h264-decoder-viewer.yml file.
name = "/tmp/img.argb"
# Obtain the keys for the shared memory and semaphores.
keySharedMemory = sysv_ipc.ftok(name, 1, True)
keySemMutex = sysv_ipc.ftok(name, 2, True)
keySemCondition = sysv_ipc.ftok(name, 3, True)
# Instantiate the SharedMemory and Semaphore objects.
shm = sysv_ipc.SharedMemory(keySharedMemory)
mutex = sysv_ipc.Semaphore(keySemCondition)
cond = sysv_ipc.Semaphore(keySemCondition)
lower_blue = numpy.array([100, 100, 30])
upper_blue = numpy.array([150, 255, 255])

lower_yellow = numpy.array([23, 41, 133])
upper_yellow = numpy.array([40, 150, 255])

lower_black = numpy.array([0, 0, 0])
upper_black = numpy.array([69, 69, 69])
from sysv_ipc import ExistentialError
class TimeoutError(Exception):
    pass

ID = 42
IPC_CREX = sysv_ipc.IPC_CREX
class MySemaphore():
    def __init__(self, path, id=ID, flag=IPC_CREX, mode=0600, value=0):
        """ 用于多进程里多个资源分享
        Semaphore( key, [flags = 0, mode = 0600, initial_value = 0] )
        flags default of 0, open an existing semaphore and raises an error if that semaphore doesn't exist.
        flags set to IPC_CREAT, the module opens the semaphore identified by key or creates a new one if no such semaphore exists.
        flags set to IPC_CREX (IPC_CREAT | IPC_EXCL), the module creates a new semaphore identified by key. If a semaphore with that key already exists, the call raises an ExistentialError. initial_value is ignored unless both of these flags are specified or if the semaphore is read-only
        """
        # path: /root/115/code/etc/g_115_acct_proc_sem
        key = sysv_ipc.ftok(path, id, silence_warning = True)
        if key < 0: raise Exception('ftok error.path:%s'%path)
        self.sem = sysv_ipc.Semaphore( key, flag, mode, initial_value=value )

    def acquire(self, timeout=None, delta=1):
        """ decrementing the semaphore """
        try:
            self.sem.acquire( timeout, delta )
        except sysv_ipc.BusyError as e: # timeout
            raise TimeoutError('acquire timeout') # The queue is empty

    def release(self, delta = 1):
        """ increments the semaphore """
        self.sem.release(delta)

    def unlink(self):
示例#26
0
# For every filename in the tree, generate a key and associate the filename
# with that key via a dictionary.
print(f"Scanning {start_path}...")
d = {}
nfilenames = 0
for path, dirnames, filenames in os.walk(start_path):
    for filename in filenames:
        # Fully qualify the path
        filename = os.path.join(path, filename)

        nfilenames += 1

        # print("Processing %s..." % filename)

        key = sysv_ipc.ftok(filename, 42, True)

        if key not in d:
            d[key] = []

        d[key].append(filename)

# Print statistics, including files with non-unique keys.
ndups = 0
for key in d:
    if len(d[key]) > 1:
        ndups += len(d[key])
        print(key, d[key])

print(f"Out of {nfilenames} unique filenames, I found {ndups} duplicate keys.")
# range for identifying blue cones in HSV
bluRanges = [[(97, 78, 35), (130, 255, 100)]]

bluCRanges = [[(94, 50, 35), (130, 255, 100)], [(70, 30, 25), (98, 110, 80)],
              [(100, 10, 30), (180, 80, 140)]]

# range for identifying yellow cones in HSV
ylwRanges = [[(23, 60, 140), (32, 255, 255)]]

orgRanges = [[(0, 80, 110), (8, 180, 200)]]

# y-coordinate of line to check for steering direction
ySteering = 70

imgPath = "/tmp/img.argb"
keySharedMemory = sysv_ipc.ftok(imgPath, 1, True)
keySemMutex = sysv_ipc.ftok(imgPath, 2, True)
keySemCondition = sysv_ipc.ftok(imgPath, 3, True)
shm = sysv_ipc.SharedMemory(keySharedMemory)
mutex = sysv_ipc.Semaphore(keySemMutex)
cond = sysv_ipc.Semaphore(keySemCondition)

while True:
    cond.Z()

    mutex.acquire()
    shm.attach()
    buf = shm.read()
    shm.detach()
    mutex.release()
示例#28
0
############## BEGIN CONFIGURATION ##############

command_code = "power"
command_parameter = "deviceon"

############### END CONFIGURATION ###############

import sysv_ipc

msq_key = sysv_ipc.ftok('/tmp/synchronator.msq', 66, silence_warning=True)
msq = sysv_ipc.MessageQueue(msq_key)
msq_command = command_code + "=" + command_parameter + "\0"
msq.send(msq_command)
示例#29
0
import scipy.signal as sig

taajuus = 16000  #oltava vähintään 2*f1
ikk = 0.1  #ikkunan pituus sekunteina; mieluiten taajuus*ikk = 2^m
#vähintään 1/f0: 0,025, jos f0 = 40 Hz
#samaten erottelukyky = 1/ikk = 25 Hz, jos 0,04 s
Dt = 0.08  #aikaväli, jolla spektri päivitetään

Ns = int(taajuus * Dt)  #16000; 0,06 -> 960
ikks = int(taajuus * ikk)
sd.default.samplerate = taajuus
sd.default.channels = 1

### muistiin liittyminen ###
try:
    avain = ipc.ftok("/tmp", 44)
    shm = ipc.SharedMemory(avain, 0, 0)
    shm.attach(0, 0)
except Exception as e:
    print("Muistiin liittyminen pythonilla: %s" % e)

#Kohinan arvo haetaan yhdellä iteroinnilla
#käytetään 1000 Hz:n pätkiä niin, että 1. f0 - 1000+f0; 2. 500+f0 - 1500+f0 jne
n500ssa = int(500 * Dt)
alaraja = 0
ularaja = 2 * n500ssa
pit = ularaja - alaraja

toisto = 0  #vaaditaan kahta toistoa virheitten välttämiseksi
ikkuna = sig.windows.blackmanharris(ikks)
示例#30
0
def main(useShm):

    setproctitle.setproctitle("tranen: Google Translation")

    proxyport = 1080

    host1 = "https://translate.google.cn/"
    host2 = "https://translate.google.com/"

    signal.signal(signal.SIGTERM, exit)
    signal.signal(signal.SIGINT, exit)

    #proxy = { "https":"localhost:8123" }
    #proxy = { "https":"socks5://127.0.0.1:1080" }
    '''
    加了-s参数后会置1 useShm,
    表示用于取词翻译的内存共享设置
    '''
    if useShm:
        warnings.simplefilter("ignore")
        path = "/tmp"
        projectID = 2333
        key = ipc.ftok(path, projectID)
        try:
            shm = ipc.SharedMemory(key, 0, 0)
            shm.attach(0, 0)
        except Exception as e:
            print(' tranen 获取共享内存失败' + str(e))
            sys.exit(1)

    tran = Translator(targetLang='zh-CN', host=host1, proxy=None, timeout=2)
    tran1 = Translator(targetLang='en', host=host1, proxy=None, timeout=2)
    tran2 = tran
    targetTran = 'zh-CN'
    #bt = bingTranslator()
    url = 'https://cn.bing.com/dict/search?q='

    while True:
        try:
            #获取次数为1则从参数中获取,不用input获取
            if times == 1:
                In = ' '.join(list(sys.argv))
            else:
                try:
                    In = str(input('>> '))
                except KeyboardInterrupt as e:
                    cprint('Good bye~', 'yellow')
                    exit(0)
                if useShm:
                    cprint("(Google)Python接收字符串: In = " + In, 'yellow')

            if In == '':
                if useShm:
                    #空字符串标识
                    shm.write('3', 0)
                continue
            elif not isChinese(In):
                targetTran = 'zh-CN'
                tran = tran2

            elif isChinese(In):
                targetTran = 'en'
                tran = tran1

        except Exception as e:
            cprint("Python捕获异常(Google)", 'red')
            print(e)

            #退出标识
            if useShm:
                exc_type, exc_obj, exc_tb = sys.exc_info()
                print("type:" + str(exc_type))
                if exc_type == "EOFError":
                    continue
                shm.write('4', 0)

            cprint('Good bye~', 'yellow')
            #sys.exit()
            #TODO
            cprint('Not exit', 'red')
            time.sleep(1)
            continue

        try:
            if useShm:
                cprint('准备获取翻译...', 'yellow')

            if len(In) > 10000:
                In = In[:10000]
                cprint('源数据过长,截取前10000字符', 'red')

            dataList = tran.getTran(In)
        except KeyboardInterrupt as e:
            cprint('Good bye~', 'yellow')
            exit(0)
        except Exception as e:
            print(e)
            try:

                cprint('proxy connect...', 'blue')

                socks.set_default_proxy(socks.SOCKS5, '127.0.0.1', proxyport)
                socket.socket = socks.socksocket

                tran = Translator(targetLang=targetTran, host=host2, timeout=2)

                if targetTran == 'zh-CN':
                    tran2 = tran
                else:
                    tran1 = tran

                dataList = tran.getTran(In)

            except KeyboardInterrupt as e:
                cprint('Good bye~', 'yellow')
                exit(0)
            except Exception as e:
                if useShm:
                    shm.write('2', 0)
                print(e)
                '''
                如果只是获取参数的翻译结果,失败后当退出,防止
                一直失败导致无限循环尝试代理连接'''
                if times == 1:
                    sys.exit(1)

                continue

        #有用数据下标 0, 1, 11, 12
        #0: 返回到界面的直接翻译
        #1: 各词性的其他翻译
        #11:不同词性的同义词
        #12:英语解释

        #获取翻译界面的直接结果
        try:
            string = str(dataList[0][0][0])
        # 捕获空字符无法取下标的异常
        except TypeError:
            continue
            pass

        try:
            length = len(dataList[0])
        except Exception as e:
            print(e)

        if string is None:
            continue

        if useShm:
            for i in range(1, length - 1):
                #cprint('    '+dataList[0][i][0], 'cyan')
                string = string + dataList[0][i][0]

            shm.write(string + '|', 10)
            #cprint("(Google)写回共享内存:"+string+'|', 'yellow')
            offset = len((string + '|').encode('utf8'))
        else:
            for i in range(length - 1):
                cprint('    ' + dataList[0][i][0], 'cyan')

        #英语释义
        if len(dataList) > 12:
            string = tran.getSynonym(dataList[12], 0)
            #排除空字符串
            if string:
                string.replace('\n', '')
                if useShm:
                    string += '|'
                    #print("写入:"+string)
                    shm.write(string, offset + 10)
                    offset = len(string.encode('utf8')) + offset
                else:
                    print()
                    cprint("    英语释义:", 'cyan')
                    for i, ch in enumerate(string):
                        if i % 60 == 0:
                            print()
                            print('      ', end='')

                        cprint(ch, 'cyan', end='')
                    print()

        #其他翻译结果
        string = tran.getMoreTran(dataList[1], dataList[0][0][1])
        if string:
            string.replace('\n', '')
            if useShm:
                #print("写入:"+string)
                shm.write(string, offset + 10)
                offset = len(string.encode('utf8')) + offset
            else:
                '''
                因为此翻译程序用在了其他工程项目,加入了符号'|'用于满足
                其他工程, 这里没有必要使用,因此要将他们消除掉
                '''
                print()

                length = len(string)
                list1 = list(string)

                chNum = 0
                chIndex = 0
                '''去除最后一个无用的|,若只有一行翻译,一个|符号,则不要把它删掉
                不然会破会后面的逻辑,这里是判断竖线符号是否只有一个,并记下最后
                一个竖线符号的下标.
                这是段缝缝补补的代码....'''
                for i in range(length - 1, 0, -1):
                    if list1[i] == '|':
                        chNum = chNum + 1
                        if chNum >= 2:
                            break

                        chIndex = i

                if chNum != 1:
                    list1[chIndex] = '\0'
                else:
                    str1 = ''.join(list1).replace('|', '\n')

                #将list1重新连接成字符串并替代分隔符|为'\n |-'
                if chNum != 1:
                    str1 = ''.join(list1).replace('|', '\n        |-')
                try:
                    index = str.index(str1, '\n')
                    index2 = str.index(str1, ':') + 1
                    cprint('      ' + str1[:index2], 'yellow', end='')
                    if len(str1[:index].encode('utf8')) > 60:
                        for i, ch in enumerate(str1[index2:index]):
                            if i % 30 == 0 and i:
                                print()
                                cprint('           ', 'yellow', end='')

                            cprint(ch, 'yellow', end='')
                            pass
                    else:
                        cprint(str1[index2:index], 'yellow', end='')

                    if chNum != 1:
                        print()

                    if chNum != 1:
                        cprint(str1[index:])
                    else:
                        print()

                    #print()
                except:
                    pass

        #获取相关词汇
        if len(dataList) > 12:
            if dataList[11] is not None:
                string = tran.getSynonym(dataList[11])
                if string:
                    print()
                    if useShm:
                        shm.write(string, offset + 10)
                        #print("写入:"+string)
                        offset = len(string.encode('utf8')) + offset
                    else:
                        #优化显示的需要,让字符串在一行内不要显示的太长
                        cprint('    相关: ', 'green', end='\n')
                        if len(string) > 60:
                            for i, ch in enumerate(string):
                                if i % 60 == 0:
                                    print()
                                    print('     ', end='')
                                cprint(ch, 'green', end='')
                                pass
                            print()
                        else:
                            cprint('        ' + string, 'green')

        if useShm:
            '''
            用于其他工程项目,在第一字节内写入1表示
            内容写入完毕
            '''
            cprint('(Google)翻译写入完成', 'yellow')
            shm.write('\0', offset + 10)
            shm.write('1', 0)

        if times == 1:
            print()
            sys.exit(0)

        print()
示例#31
0
############## BEGIN CONFIGURATION ##############

command_code="power"
command_parameter="deviceon"

############### END CONFIGURATION ###############

import sysv_ipc

msq_key=sysv_ipc.ftok('/tmp/synchronator.msq', 66, silence_warning = True)
msq  = sysv_ipc.MessageQueue(msq_key)
msq_command=command_code + "=" + command_parameter + "\0"
msq.send(msq_command)
示例#32
0
    raise TimeoutError('alarm timeout')

class MyQueue():
    def __init__(self, name, id=42, flag=sysv_ipc.IPC_CREAT, mode=0600, msgmax=2048, destroy=0):
        """
        destroy: 1 unlink queue when close()
        MessageQueue( key, [flags = 0, mode = 0600, max_message_size = 2048] )
        flags set to the default of 0, attempts to open an existing message queue identified by key and raises a ExistentialError if it doesn't exist.
        flags set to IPC_CREAT, opens the message queue identified by key or creates a new one if no such queue exists.
        flags set to IPC_CREX (IPC_CREAT | IPC_EXCL), creates a new message queue identified by key. If a queue with that key already exists, the call raises a ExistentialError.
        """
        if not os.path.exists( name ): raise Exception( 'queue file:%s not exist' % name )
        # name: /root/115/code/etc/g_115_acct_proc_queue
        self.destroy = destroy
        self.name = name
        key = sysv_ipc.ftok(self.name, id, silence_warning = True)
        if key < 0: raise Exception('ftok error.name:%s'%self.name)
        self.mq = sysv_ipc.MessageQueue( key, flag, mode, msgmax )

    def send(self, msg, timeout=None, type=1):
        """ params:
                timeout == None 阻塞
                timeout <= 0, 马上返回, 发送失败时raise BusyError
                timeout > 0, 等待n秒, 发送失败raise BusyError
                block: specifies whether should wait if the message can't be sent (if, for example, the queue is full).
                        When block is False, will raise a BusyError if the message can't be sent immediately
                type: must be > 0
            return: None. if Success
                    raise Exception. when Error
        """
        try:
示例#33
0
start_path = os.path.abspath(start_path)

# For every filename in the tree, generate a key and associate the filename
# with that key via a dictionary.
d = { }
nfilenames = 0
for path, dirnames, filenames in os.walk(start_path):
    for filename in filenames:
        # Fully qualify the path
        filename = os.path.join(path, filename)

        nfilenames += 1

        #print "Processing %s..." % filename

        key = sysv_ipc.ftok(filename, 42, True)

        if key not in d:
            d[key] = [ ]

        d[key].append(filename)

# Print statistics, including files with non-unique keys.
ndups = 0
for key in d:
    if len(d[key]) > 1:
        ndups += len(d[key])
        print key, d[key]

print "Out of {0} unique filenames, I found {1} duplicate keys.".format(nfilenames, ndups)
示例#34
0
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hcf:k:px", ["help", ])
    except getopt.GetoptError, err:
        print str(err)
        usage()

    flags = 0
    for o, a in opts:
        if o in ("-h", "--help"):
            usage()
            sys.exit()
        elif o in ("-c", ):
            flags |= sysv_ipc.IPC_CREAT
        elif o in ("-f", ):
            key = sysv_ipc.ftok(a, 1)
        elif o in ("-k", ):
            key = int(a, 0)
        elif o in ("-p", ):
            key = sysv_ipc.IPC_PRIVATE
        elif o in ("-x", ):
            flags |= sysv_ipc.IPC_EXCL
        else:
            assert False, "unhandled option"

    mq = sysv_ipc.MessageQueue(key, flags=flags, mode=0666)
    print "msqid :", mq.id

if __name__ == '__main__':
    main()
示例#35
0
    f.write(line)


# Start Displaying thread and init shared memory connection
def startDisplay():
    print("[INFO]: Starting display thread...")
    call(["./SACDisplayMixer/OGLESSimpleImageWithIPC"]) 
############################


######## main init #########
th1 = Thread(target=startDisplay)
th1.start()
time.sleep(1)

key = ipc.ftok("/home/pi/SACLeptonRPi", ord('i'))
shm = ipc.SharedMemory(key, 0, 0)
shm.attach()
print("[INFO]: Shared memory key " + str(key) + " with pointer " +  str(shm))

# Initialize PiCamera
cameraWidth = 640
cameraHeight = 480
camera = PiCamera()
camera.resolution = (cameraWidth,cameraHeight)
camera.framerate = 10

#camera.annotate_foreground = Color(y=0.4, u=-0.05, v=0.615)
#camera.annotate_text = 'Hallo!'
camera.meter_mode = 'spot'
camera.hflip = True