本文整理汇总了Python中twisted.internet.reactor.spawnProcess函数的典型用法代码示例。如果您正苦于以下问题:Python spawnProcess函数的具体用法?Python spawnProcess怎么用?Python spawnProcess使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了spawnProcess函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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)
示例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
示例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
示例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)
示例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
示例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,
)
示例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'])
示例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
)
示例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)
示例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
示例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)
示例13: execCommand
def execCommand( self, protocol, cmd ):
c = cmd.split()
if c[0] == 'scp':
reactor.spawnProcess(
protocol,
'scp', ['scp', '-t', '-d', 'file' ] )
示例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
示例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