本文整理匯總了Python中twisted.internet.utils.getProcessValue方法的典型用法代碼示例。如果您正苦於以下問題:Python utils.getProcessValue方法的具體用法?Python utils.getProcessValue怎麽用?Python utils.getProcessValue使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類twisted.internet.utils
的用法示例。
在下文中一共展示了utils.getProcessValue方法的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _uncleanSocketTest
# 需要導入模塊: from twisted.internet import utils [as 別名]
# 或者: from twisted.internet.utils import getProcessValue [as 別名]
def _uncleanSocketTest(self, callback):
self.filename = self.mktemp()
source = networkString((
"from twisted.internet import protocol, reactor\n"
"reactor.listenUNIX(%r, protocol.ServerFactory(),"
"wantPID=True)\n") % (self.filename,))
env = {b'PYTHONPATH': FilePath(
os.pathsep.join(sys.path)).asBytesMode().path}
pyExe = FilePath(sys.executable).asBytesMode().path
d = utils.getProcessValue(pyExe, (b"-u", b"-c", source), env=env)
d.addCallback(callback)
return d
示例2: test_value
# 需要導入模塊: from twisted.internet import utils [as 別名]
# 或者: from twisted.internet.utils import getProcessValue [as 別名]
def test_value(self):
"""
The L{Deferred} returned by L{getProcessValue} is fired with the exit
status of the child process.
"""
scriptFile = self.makeSourceFile(["raise SystemExit(1)"])
d = utils.getProcessValue(self.exe, ['-u', scriptFile])
return d.addCallback(self.assertEqual, 1)
示例3: test_getProcessValuePath
# 需要導入模塊: from twisted.internet import utils [as 別名]
# 或者: from twisted.internet.utils import getProcessValue [as 別名]
def test_getProcessValuePath(self):
"""
L{getProcessValue} runs the given command with the working directory
given by the C{path} parameter.
"""
def check(result, ignored):
self.assertEqual(result, 0)
return self._pathTest(utils.getProcessValue, check)
示例4: _run_crawler
# 需要導入模塊: from twisted.internet import utils [as 別名]
# 或者: from twisted.internet.utils import getProcessValue [as 別名]
def _run_crawler(self, project, spider, job_id, payload):
#-----------------------------------------------------------------------
# Unzip to a temporary directory
#-----------------------------------------------------------------------
temp_dir = tempfile.mkdtemp()
archive = os.path.join(self.project_store, project + '.zip')
unzip = find_executable('unzip')
if unzip is None:
raise EnvironmentError('Please install unzip')
ret_code = yield getProcessValue(unzip, args=(archive,), path=temp_dir)
if ret_code != 0:
shutil.rmtree(temp_dir)
msg = 'Unable to unzip with {}. Archive corrupted?'.format(unzip)
self.log.error(msg)
raise IOError('Cannot unzip the project archive')
#-----------------------------------------------------------------------
# Run the crawler
#-----------------------------------------------------------------------
temp_proj_dir = os.path.join(temp_dir, project)
env = {'SPIDER_DATA_DIR': self.spider_data_dir}
args = ['crawl', spider]
if payload != '{}':
args += ['-a', 'payload=' + payload]
process, finished = run_process('scrapy', args, job_id,
self.log_dir, env=env,
path=temp_proj_dir)
#-----------------------------------------------------------------------
# Clean up
#-----------------------------------------------------------------------
def clean_up(status):
shutil.rmtree(temp_dir)
return status
finished.addBoth(clean_up)
returnValue((process, finished))
#---------------------------------------------------------------------------
示例5: _uncleanSocketTest
# 需要導入模塊: from twisted.internet import utils [as 別名]
# 或者: from twisted.internet.utils import getProcessValue [as 別名]
def _uncleanSocketTest(self, callback):
self.filename = self.mktemp()
source = ("from twisted.internet import protocol, reactor\n"
"reactor.listenUNIX(%r, protocol.ServerFactory(), wantPID=True)\n") % (self.filename,)
env = {'PYTHONPATH': os.pathsep.join(sys.path)}
d = utils.getProcessValue(sys.executable, ("-u", "-c", source), env=env)
d.addCallback(callback)
return d
示例6: test_getProcessValueDefaultPath
# 需要導入模塊: from twisted.internet import utils [as 別名]
# 或者: from twisted.internet.utils import getProcessValue [as 別名]
def test_getProcessValueDefaultPath(self):
"""
If no value is supplied for the C{path} parameter, L{getProcessValue}
runs the given command in the same working directory as the parent
process and succeeds even if the current working directory is not
accessible.
"""
def check(result, ignored):
self.assertEqual(result, 0)
return self._defaultPathTest(utils.getProcessValue, check)
示例7: testValue
# 需要導入模塊: from twisted.internet import utils [as 別名]
# 或者: from twisted.internet.utils import getProcessValue [as 別名]
def testValue(self):
exe = sys.executable
scriptFile = self.makeSourceFile([
"import sys",
"sys.exit(1)"
])
d = utils.getProcessValue(exe, ['-u', scriptFile])
return d.addCallback(self.assertEquals, 1)
示例8: execute
# 需要導入模塊: from twisted.internet import utils [as 別名]
# 或者: from twisted.internet.utils import getProcessValue [as 別名]
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}
"""
# PubkeyAcceptedKeyTypes does not exist prior to OpenSSH 7.0 so we
# first need to check if we can set it. If we can, -V will just print
# the version without doing anything else; if we can't, we will get a
# configuration error.
d = getProcessValue(
which('ssh')[0], ('-o', 'PubkeyAcceptedKeyTypes=ssh-dss', '-V'))
def hasPAKT(status):
if status == 0:
opts = '-oPubkeyAcceptedKeyTypes=ssh-dss '
else:
opts = ''
process.deferred = defer.Deferred()
# Pass -F /dev/null to avoid the user's configuration file from
# being loaded, as it may contain settings that cause our tests to
# fail or hang.
cmdline = ('ssh -2 -l testuser -p %i '
'-F /dev/null '
'-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 ') + opts + sshArgs + \
' 127.0.0.1 ' + remoteCommand
port = self.conchServer.getHost().port
cmds = (cmdline % port).split()
encodedCmds = []
for cmd in cmds:
if isinstance(cmd, unicode):
cmd = cmd.encode("utf-8")
encodedCmds.append(cmd)
reactor.spawnProcess(process, which('ssh')[0], encodedCmds)
return process.deferred
return d.addCallback(hasPAKT)
示例9: test_extendedAttributes
# 需要導入模塊: from twisted.internet import utils [as 別名]
# 或者: from twisted.internet.utils import getProcessValue [as 別名]
def test_extendedAttributes(self):
"""
Test the return of extended attributes by the server: the sftp client
should ignore them, but still be able to parse the response correctly.
This test is mainly here to check that
L{filetransfer.FILEXFER_ATTR_EXTENDED} has the correct value.
"""
fn = self.mktemp()
with open(fn, 'w') as f:
f.write("ls .\nexit")
port = self.server.getHost().port
oldGetAttr = FileTransferForTestAvatar._getAttrs
def _getAttrs(self, s):
attrs = oldGetAttr(self, s)
attrs["ext_foo"] = "bar"
return attrs
self.patch(FileTransferForTestAvatar, "_getAttrs", _getAttrs)
self.server.factory.expectedLoseConnection = True
# PubkeyAcceptedKeyTypes does not exist prior to OpenSSH 7.0 so we
# first need to check if we can set it. If we can, -V will just print
# the version without doing anything else; if we can't, we will get a
# configuration error.
d = getProcessValue(
'ssh', ('-o', 'PubkeyAcceptedKeyTypes=ssh-dss', '-V'))
def hasPAKT(status):
if status == 0:
args = ('-o', 'PubkeyAcceptedKeyTypes=ssh-dss')
else:
args = ()
# Pass -F /dev/null to avoid the user's configuration file from
# being loaded, as it may contain settings that cause our tests to
# fail or hang.
args += ('-F', '/dev/null',
'-o', 'IdentityFile=dsa_test',
'-o', 'UserKnownHostsFile=kh_test',
'-o', 'HostKeyAlgorithms=ssh-rsa',
'-o', 'Port=%i' % (port,), '-b', fn, 'testuser@127.0.0.1')
return args
def check(result):
self.assertEqual(result[2], 0)
for i in [b'testDirectory', b'testRemoveFile',
b'testRenameFile', b'testfile1']:
self.assertIn(i, result[0])
d.addCallback(hasPAKT)
d.addCallback(lambda args: getProcessOutputAndValue('sftp', args))
return d.addCallback(check)
示例10: _on_torrent_finished
# 需要導入模塊: from twisted.internet import utils [as 別名]
# 或者: from twisted.internet.utils import getProcessValue [as 別名]
def _on_torrent_finished(self, torrent_id):
"""
This is called when a torrent finishes and checks if any files to extract.
"""
tid = component.get("TorrentManager").torrents[torrent_id]
tid_status = tid.get_status(["save_path", "name"])
files = tid.get_files()
for f in files:
file_root, file_ext = os.path.splitext(f["path"])
file_ext_sec = os.path.splitext(file_root)[1]
if file_ext_sec and file_ext_sec + file_ext in EXTRACT_COMMANDS:
file_ext = file_ext_sec + file_ext
elif file_ext not in EXTRACT_COMMANDS or file_ext_sec == '.tar':
log.warning("EXTRACTOR: Can't extract file with unknown file type: %s" % f["path"])
continue
cmd = EXTRACT_COMMANDS[file_ext]
# Now that we have the cmd, lets run it to extract the files
fpath = os.path.join(tid_status["save_path"], os.path.normpath(f["path"]))
# Get the destination path
dest = os.path.normpath(self.config["extract_path"])
if self.config["use_name_folder"]:
name = tid_status["name"]
dest = os.path.join(dest, name)
# Override destination if in_place_extraction is set
if self.config["in_place_extraction"]:
name = tid_status["name"]
save_path = tid_status["save_path"]
dest = os.path.join(save_path,name)
# Create the destination folder if it doesn't exist
if not os.path.exists(dest):
try:
os.makedirs(dest)
except Exception, e:
log.error("EXTRACTOR: Error creating destination folder: %s", e)
return
def on_extract_success(result, torrent_id, fpath):
# XXX: Emit an event
log.info("EXTRACTOR: Extract successful: %s (%s)", fpath, torrent_id)
def on_extract_failed(result, torrent_id, fpath):
# XXX: Emit an event
log.error("EXTRACTOR: Extract failed: %s (%s)", fpath, torrent_id)
# Run the command and add some callbacks
log.debug("EXTRACTOR: Extracting %s with %s %s to %s", fpath, cmd[0], cmd[1], dest)
d = getProcessValue(cmd[0], cmd[1].split() + [str(fpath)], {}, str(dest))
d.addCallback(on_extract_success, torrent_id, fpath)
d.addErrback(on_extract_failed, torrent_id, fpath)