本文整理汇总了Python中twisted.internet.reactor.spawnProcess函数的典型用法代码示例。如果您正苦于以下问题:Python spawnProcess函数的具体用法?Python spawnProcess怎么用?Python spawnProcess使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了spawnProcess函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: buildProtocol
def buildProtocol(self, addr):
now = time.time()
if now - self.last_update > self.timeout: # primitive DoS prevention
self.last_update = now
# Note: this does not inherit *any* environment
reactor.spawnProcess(GitPull(), 'git', args=['git', 'pull'])
return protocol.ServerFactory.buildProtocol(self, addr)
开发者ID:Janno,项目名称:pyhkal2,代码行数:7,代码来源:github.py
示例2: deliverJob
def deliverJob(self):
# returns a Deferred that fires when the job has been delivered
if self.connect == "ssh":
tryhost = self.getopt("tryhost")
tryuser = self.getopt("username")
trydir = self.getopt("trydir")
argv = ["ssh", "-l", tryuser, tryhost, "buildbot", "tryserver", "--jobdir", trydir]
# now run this command and feed the contents of 'job' into stdin
pp = RemoteTryPP(self.jobfile)
reactor.spawnProcess(pp, argv[0], argv, os.environ)
d = pp.d
return d
if self.connect == "pb":
user = self.getopt("username")
passwd = self.getopt("passwd")
master = self.getopt("master")
tryhost, tryport = master.split(":")
tryport = int(tryport)
f = pb.PBClientFactory()
d = f.login(credentials.UsernamePassword(user, passwd))
reactor.connectTCP(tryhost, tryport, f)
d.addCallback(self._deliverJob_pb)
return d
raise RuntimeError("unknown connecttype '%s', should be 'ssh' or 'pb'" % self.connect)
开发者ID:ahussein,项目名称:buildbot,代码行数:27,代码来源:tryclient.py
示例3: testManyProcesses
def testManyProcesses(self):
def _check(results, protocols):
for p in protocols:
self.assertEquals(p.stages, [1, 2, 3, 4, 5], "[%d] stages = %s" % (id(p.transport), str(p.stages)))
# test status code
f = p.reason
f.trap(error.ProcessTerminated)
self.assertEquals(f.value.exitCode, 23)
exe = sys.executable
scriptPath = util.sibpath(__file__, "process_tester.py")
args = [exe, "-u", scriptPath]
protocols = []
deferreds = []
for i in xrange(50):
p = TestManyProcessProtocol()
protocols.append(p)
reactor.spawnProcess(p, exe, args, env=None)
deferreds.append(p.deferred)
deferredList = defer.DeferredList(deferreds, consumeErrors=True)
deferredList.addCallback(_check, protocols)
return deferredList
开发者ID:andrewbird,项目名称:vodafone-mobile-connect,代码行数:25,代码来源:test_process.py
示例4: testChildResolve
def testChildResolve(self):
# I've seen problems with reactor.run under gtk2reactor. Spawn a
# child which just does reactor.resolve after the reactor has
# started, fail if it does not complete in a timely fashion.
helperPath = os.path.abspath(self.mktemp())
helperFile = open(helperPath, 'w')
# Eeueuuggg
reactorName = reactor.__module__
helperFile.write(resolve_helper % {'reactor': reactorName})
helperFile.close()
env = os.environ.copy()
env['PYTHONPATH'] = os.pathsep.join(sys.path)
helperDeferred = Deferred()
helperProto = ChildResolveProtocol(helperDeferred)
reactor.spawnProcess(helperProto, sys.executable, ("python", "-u", helperPath), env)
def cbFinished((reason, output, error)):
# If the output is "done 127.0.0.1\n" we don't really care what
# else happened.
output = ''.join(output)
if output != 'done 127.0.0.1\n':
self.fail((
"The child process failed to produce the desired results:\n"
" Reason for termination was: %r\n"
" Output stream was: %r\n"
" Error stream was: %r\n") % (reason.getErrorMessage(), output, ''.join(error)))
helperDeferred.addCallback(cbFinished)
return helperDeferred
开发者ID:KatiaBorges,项目名称:exeLearning,代码行数:34,代码来源:test_internet.py
示例5: run
def run(self):
started = defer.Deferred()
self.serverStopped = defer.Deferred()
self.processStopped = defer.Deferred()
fact = protocol.Factory()
fact.protocol = ivc.IVC4300Protocol
fact.onConnectionMade = started
fact.onConnectionLost = self.serverStopped
proc = ivc.IVC4300Process(self.processStopped)
executable = "C:/smacCapture/capture2.exe"
path, bin = os.path.split(executable)
PORT = 6544
port = reactor.listenTCP(PORT, fact)
reactor.spawnProcess(proc, executable, [bin], {}, path)
self.protocol = yield started
self.portStopped = defer.maybeDeferred(port.stopListening)
self.portStopped.addCallback(lambda _: log.msg("Stopped listening"))
yield self.protocol.start()
print "Start recording session {0} (parent task is {1})".format(self.session.id, self.parent)
开发者ID:SMAC,项目名称:ivc-recorder,代码行数:25,代码来源:recorder.py
示例6: execute
def execute(self, remoteCommand, process, sshArgs=''):
"""
Connects to the SSH server started in L{ConchServerSetupMixin.setUp} by
running the 'ssh' command line tool.
@type remoteCommand: str
@param remoteCommand: The command (with arguments) to run on the
remote end.
@type process: L{ConchTestOpenSSHProcess}
@type sshArgs: str
@param sshArgs: Arguments to pass to the 'ssh' process.
@return: L{defer.Deferred}
"""
process.deferred = defer.Deferred()
cmdline = ('ssh -2 -l testuser -p %i '
'-oUserKnownHostsFile=kh_test '
'-oPasswordAuthentication=no '
# Always use the RSA key, since that's the one in kh_test.
'-oHostKeyAlgorithms=ssh-rsa '
'-a '
'-i dsa_test ') + sshArgs + \
' 127.0.0.1 ' + remoteCommand
port = self.conchServer.getHost().port
cmds = (cmdline % port).split()
reactor.spawnProcess(process, "ssh", cmds)
return process.deferred
开发者ID:ChimmyTee,项目名称:oh-mainline,代码行数:29,代码来源:test_conch.py
示例7: start_canopen
def start_canopen(self):
# Avvio il server CANOPEN
# usePTY serve ad evitare l'ECHO
# INFO: uso stdbuf per evitare il buffering dell'output se non in terminale
if self.config.isFake:
reactor.spawnProcess(
self.canopen,
"/usr/bin/stdbuf",
args=[
"stdbuf",
"--output=L",
"--input=0",
"/opt/spinitalia/alma3d_canopenshell",
"fake",
"load#libcanfestival_can_socket.so,0,1M,8",
],
env=os.environ,
usePTY=False,
)
else:
reactor.spawnProcess(
self.canopen,
"/usr/bin/stdbuf",
args=[
"stdbuf",
"--output=L",
"--input=0",
"/opt/spinitalia/alma3d_canopenshell",
"load#libcanfestival_can_socket.so,0,1M,8",
],
env=os.environ,
usePTY=False,
)
开发者ID:henry-spinitalia,项目名称:alma_tcp_server,代码行数:34,代码来源:alma3d_control_service.py
示例8: connectionMade
def connectionMade(self):
from twisted.internet import reactor
log.msg("launch a new process on each new connection")
self.pp = ProcessProtocol()
self.pp.factory = self
reactor.spawnProcess(self.pp, sys.executable,
[sys.executable, '-u', 'wait_for_makey.py'])
开发者ID:kelly-ry4n,项目名称:electrokit,代码行数:7,代码来源:server.py
示例9: _task_reinstall
def _task_reinstall(self, packages=[]):
if packages:
reactor.spawnProcess(
self,
'/usr/bin/apt-get',
['apt-get', '-y', '--force-yes', '-f', '--purge', '--reinstall', 'install'] + map(str, packages), env=None
)
开发者ID:AlfredArouna,项目名称:jolicloud-restore-utility,代码行数:7,代码来源:restore_utility.py
示例10: launch_player
def launch_player(self, test=False):
if self.playercmd_args is not None:
self.player_args = [self.player_path] + self.playercmd_args.split()
for proc in psutil.process_iter():
if proc.name() == self.player:
log.msg("Player process found", loglevel=logging.DEBUG)
self._managed = False
self.extpid = proc.pid
self.juststarted = False
reactor.callWhenRunning(self.connect) # @UndefinedVariable
if test:
if self._errors > 5:
try:
self.protocol.shutdown()
except:
proc.kill()
return False
else:
self._errors += 1
return True
return None
if test:
return False
self._managed = True
try:
reactor.spawnProcess( # @UndefinedVariable
PlayerProcess(self), self.player_path, self.player_args, env=os.environ
)
except:
log.err("Program unknown : %s" % self.player_args)
开发者ID:bverdu,项目名称:onDemand,代码行数:30,代码来源:mprisclient.py
示例11: execute
def execute(self, remoteCommand, process, sshArgs=""):
"""
As for L{OpenSSHClientTestCase.execute}, except it runs the 'conch'
command line tool, not 'ssh'.
"""
process.deferred = defer.Deferred()
port = self.conchServer.getHost().port
cmd = (
(
"-p %i -l testuser "
"--known-hosts kh_test "
"--user-authentications publickey "
"--host-key-algorithms ssh-rsa "
"-a "
"-i dsa_test "
"-v "
)
% port
+ sshArgs
+ " 127.0.0.1 "
+ remoteCommand
)
cmds = _makeArgs(cmd.split())
log.msg(str(cmds))
env = os.environ.copy()
env["PYTHONPATH"] = os.pathsep.join(sys.path)
reactor.spawnProcess(process, sys.executable, cmds, env=env)
return process.deferred
开发者ID:ssilverek,项目名称:kodb,代码行数:28,代码来源:test_conch.py
示例12: sendCodeReview
def sendCodeReview(self, project, revision, message=None, verified=0, reviewed=0):
gerrit_version = self.getCachedVersion()
if (verified or reviewed) and gerrit_version is None:
self.callWithVersion(lambda: self.sendCodeReview(project, revision, message, verified, reviewed))
return
command = self._gerritCmd("review", "--project %s" % str(project))
if message:
command.append("--message '%s'" % message.replace("'", "\""))
if verified:
assert(gerrit_version)
if gerrit_version < LooseVersion("2.6"):
command.extend(["--verified %d" % int(verified)])
else:
command.extend(["--label Verified=%d" % int(verified)])
if reviewed:
assert(gerrit_version)
if gerrit_version < LooseVersion("2.6"):
command.extend(["--code-review %d" % int(reviewed)])
else:
command.extend(["--label Code-Review=%d" % int(reviewed)])
command.append(str(revision))
print command
reactor.spawnProcess(self.LocalPP(self), command[0], command)
开发者ID:OXTbuilders,项目名称:legacy2,代码行数:27,代码来源:status_gerrit.py
示例13: execCommand
def execCommand( self, protocol, cmd ):
c = cmd.split()
if c[0] == 'scp':
reactor.spawnProcess(
protocol,
'scp', ['scp', '-t', '-d', 'file' ] )
开发者ID:devinjacobson,项目名称:prediction,代码行数:7,代码来源:SCPServer.py
示例14: runCommand
def runCommand(self, command, error=False,
script="calendarserver_command_gateway"):
"""
Run the given command by feeding it as standard input to
calendarserver_command_gateway in a subprocess.
"""
if isinstance(command, unicode):
command = command.encode("utf-8")
sourceRoot = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
python = sys.executable
script = os.path.join(sourceRoot, "bin", script)
args = [python, script, "-f", self.configFileName]
if error:
args.append("--error")
cwd = sourceRoot
deferred = Deferred()
reactor.spawnProcess(CapturingProcessProtocol(deferred, command), python, args, env=os.environ, path=cwd)
output = yield deferred
try:
plist = readPlistFromString(output)
except xml.parsers.expat.ExpatError, e:
print("Error (%s) parsing (%s)" % (e, output))
raise
开发者ID:svn2github,项目名称:calendarserver-raw,代码行数:28,代码来源:test_gateway.py
示例15: testCallBeforeStartupUnexecuted
def testCallBeforeStartupUnexecuted(self):
progname = self.mktemp()
progfile = open(progname, 'w')
progfile.write(_callBeforeStartupProgram % {'reactor': reactor.__module__})
progfile.close()
def programFinished(result):
(out, err, reason) = result
if reason.check(error.ProcessTerminated):
self.fail("Process did not exit cleanly (out: %s err: %s)" % (out, err))
if err:
log.msg("Unexpected output on standard error: %s" % (err,))
self.failIf(out, "Expected no output, instead received:\n%s" % (out,))
def programTimeout(err):
err.trap(error.TimeoutError)
proto.signalProcess('KILL')
return err
env = os.environ.copy()
env['PYTHONPATH'] = os.pathsep.join(sys.path)
d = defer.Deferred().addCallbacks(programFinished, programTimeout)
proto = ThreadStartupProcessProtocol(d)
reactor.spawnProcess(proto, sys.executable, ('python', progname), env)
return d
开发者ID:12019,项目名称:OpenWrt_Luci_Lua,代码行数:26,代码来源:test_threads.py
示例16: main
def main():
(parser, options, args) = parse_args()
if len(args) == 0:
parser.print_usage()
sys.exit(1)
if options.verbose:
logger.setLevel(logging.DEBUG)
logger.debug("verbose logging enabled.")
# ---------------------------------------------------------------
# Terminate the Twisted reactor on a signal.
# ---------------------------------------------------------------
def signal_handler(signum, stackframe):
reactor.callFromThread(reactor.stop)
signal.signal(signal.SIGINT, signal_handler)
# ---------------------------------------------------------------
# ---------------------------------------------------------------
# Spawn the process specified when the reactor starts.
#
# We want to run it up to the run count, and after the final
# iteration summarise the findings.
# ---------------------------------------------------------------
measure_protocol = MeasureProtocol(args = args)
reactor.spawnProcess(measure_protocol, args[0], args)
# ---------------------------------------------------------------
reactor.run()
开发者ID:asimihsan,项目名称:going_faster_with_python,代码行数:28,代码来源:measureproc.py
示例17: run_server
def run_server(fd=None, port=None, procs=None, verbose=False):
if args.verbose:
log.startLogging(stdout)
environ['SOLEDAD_LOG_TO_STDOUT'] = '1'
config = get_config()
path = config["blobs_path"]
if not port:
port = int(config["blobs_port"])
root = Resource()
root.putChild('blobs', BlobsResource("filesystem", path))
factory = Site(root)
if fd is None:
# Create a new listening port and several other
# processes to help out.
if procs is None:
procs = cpu_count()
log.msg('A total of %d processes will listen on port %d.' % (procs, port))
port = reactor.listenTCP(port, factory)
for i in range(procs - 1):
reactor.spawnProcess(
None, executable, [executable, __file__, str(port.fileno())],
childFDs={0: 0, 1: 1, 2: 2, port.fileno(): port.fileno()},
env=environ)
else:
# Another process created the port, just start listening on it.
log.msg('Adopting file descriptor %d...' % fd)
port = reactor.adoptStreamPort(fd, AF_INET, factory)
reactor.run()
开发者ID:leapcode,项目名称:soledad-perf,代码行数:32,代码来源:blobs-server.py
示例18: dataReceived
def dataReceived(self, data):
#if VERBOSE: print "Received",repr(data)
if self.state == 0 and data == "Hopper":
self.state = 1
data = data[6:]
self.transport.write(struct.pack("<H", HOPPER_GDB_PROTOCOL_VERSION))
if self.state == 1 and len(data) >= 2:
self.state = 2
remote_version, = struct.unpack("<H", data[:2])
data = data[2:]
if remote_version != HOPPER_GDB_PROTOCOL_VERSION:
if VERBOSE: print "Unsupported version",remote_version
self.transport.loseConnection()
return
if self.state == 2 and len(data) > 0:
self.gdb_arch = data.strip("\x00")
self.state = 3
data = ""
if self.state == 3:
if sys.platform == "darwin":
launch_args = ["gdb", "--arch=%s"%self.gdb_arch, "--quiet", "--nx", "--interpreter=mi1"]
else:
launch_args = ["gdb", "--quiet", "--nx", "--interpreter=mi1"]
if self.override_args and len(self.override_args):
launch_args.extend(["--args", self.override_file]+self.override_args)
elif self.override_file:
launch_args.append(self.override_file)
if VERBOSE: print "Launch:",str(launch_args)
self.gdb = GDBProtocol(self)
reactor.spawnProcess(self.gdb, "/usr/bin/gdb", args=launch_args)
if self.state == 4 and self.gdb != None:
if VERBOSE: print "WRITE TO GDB",repr(data)
data = self.modifyCommand(data)
self.gdb.transport.write(data)
开发者ID:0day1day,项目名称:HopperScripts,代码行数:34,代码来源:Hopper+GDB+to+GDB.py
示例19: get_status
def get_status( hg_repo_dir, from_revision = None, to_revision = None ):
hg_repo_dir = os.path.expanduser( os.path.expandvars(hg_repo_dir) )
if not os.path.isdir( os.path.join(hg_repo_dir, '.hg') ):
return defer.fail( Exception('Invalid HG Repository: %s' % hg_repo_dir) )
rev_str = ''
if from_revision:
rev_str = '%s' % from_revision
if to_revision:
rev_str = rev_str + ':%s' % to_revision
sp = HgStatusProto()
args = [HG_PATH, 'status']
if rev_str:
args.append( '--rev' )
args.append( rev_str )
reactor.spawnProcess(sp, HG_PATH, args=args, env=None, path=hg_repo_dir)
return sp.d
开发者ID:cocagne,项目名称:scratch,代码行数:27,代码来源:hg_interface.py
示例20: startProcess
def startProcess(self, childClass, parentClass):
from twisted.internet import reactor
childClassPath = self._checkRoundTrip(childClass)
prot = self.connectorFactory(parentClass())
bootstrapPath = os.path.join(os.path.dirname(__file__), 'bootstrap.py')
# Insert required modules into PYTHONPATH if they lie outside the
# system import locations.
env = os.environ.copy()
pythonPath = []
for pkg in self.packages:
p = os.path.dirname(imp.find_module(pkg)[1])
if (p.startswith(os.path.join(sys.prefix, 'lib'))
or p.startswith(os.path.join(sys.prefix, 'lib64'))):
continue
pythonPath.append(p)
pythonPath.extend(env.get('PYTHONPATH', '').split(os.pathsep))
env['PYTHONPATH'] = os.pathsep.join(pythonPath)
args = (sys.executable, bootstrapPath, childClassPath)
fds = {connector.TO_CHILD: 'w', connector.FROM_CHILD: 'r'}
if self.debug:
fds.update({0: 0, 1: 1, 2: 2})
else:
fds.update({0: 'w', 1: 'r', 2: 'r'})
reactor.spawnProcess(prot, sys.executable, args, env, childFDs=fds)
return prot
开发者ID:pombreda,项目名称:rmake3,代码行数:28,代码来源:pool.py
注:本文中的twisted.internet.reactor.spawnProcess函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论