Python os 模块,spawnvp() 实例源码
我们从Python开源项目中,提取了以下15个代码示例,用于说明如何使用os.spawnvp()。
def spawn(self, filepath, configuration_alias, replace=False):
"""Spawns uWSGI using the given configuration module.
:param str|unicode filepath:
:param str|unicode configuration_alias:
:param bool replace: Whether a new process should replace current one.
"""
# Pass --conf as an argument to have a chance to use
# touch reloading form .py configuration file change.
args = ['uwsgi', '--ini', 'exec://%s %s --conf %s' % (self.binary_python, filepath, configuration_alias)]
if replace:
return os.execvp('uwsgi', args)
return os.spawnvp(os.P_NOWAIT, 'uwsgi', args)
def run_command_killable(*argv):
filename = argv[0]
status = None
pid = os.spawnvp(os.P_NOWAIT, filename, argv)
try:
status = waitpid_reap_other_children(pid)
except BaseException as s:
warn("An error occurred. Aborting.")
stop_child_process(filename, pid)
raise
if status != 0:
if status is None:
error("%s exited with unknown status\n" % filename)
else:
error("%s failed with status %d\n" % (filename, os.WEXITSTATUS(status)))
sys.exit(1)
def spawn(command, args):
print command, ' '.join(args[1:])
ret = os.spawnvp(os.P_WAIT, command, args)
if ret != 0:
raise RuntimeError("could not run " + command)
# Subclass pexpect.spawn to add logging of expect() calls
def slog(self, message):
slog_info(self.structured_log_f, message)
# Wrapper around pexpect.spawn to let us log the command for
# debugging. Note that unlike os.spawnvp, args[0] is not
# the name of the command.
def create_spawnv(original_name):
def new_spawnv(mode, path, args):
"""
os.spawnv(mode, path, args)
os.spawnvp(mode, file, args)
"""
import os
send_process_created_message()
return getattr(os, original_name)(mode, path, patch_args(args))
return new_spawnv
def patch_new_process_functions_with_warning():
monkey_patch_os('execl', create_warn_multiproc)
monkey_patch_os('execle', create_warn_multiproc)
monkey_patch_os('execlp', create_warn_multiproc)
monkey_patch_os('execlpe', create_warn_multiproc)
monkey_patch_os('execv', create_warn_multiproc)
monkey_patch_os('execve', create_warn_multiproc)
monkey_patch_os('execvp', create_warn_multiproc)
monkey_patch_os('execvpe', create_warn_multiproc)
monkey_patch_os('spawnl', create_warn_multiproc)
monkey_patch_os('spawnle', create_warn_multiproc)
monkey_patch_os('spawnlp', create_warn_multiproc)
monkey_patch_os('spawnlpe', create_warn_multiproc)
monkey_patch_os('spawnv', create_warn_multiproc)
monkey_patch_os('spawnve', create_warn_multiproc)
monkey_patch_os('spawnvp', create_warn_multiproc)
monkey_patch_os('spawnvpe', create_warn_multiproc)
if sys.platform != 'win32':
monkey_patch_os('fork', create_warn_multiproc)
try:
import _posixsubprocess
monkey_patch_module(_posixsubprocess, 'fork_exec', create_warn_fork_exec)
except ImportError:
pass
else:
# Windows
try:
import _subprocess
except ImportError:
import _winapi as _subprocess
monkey_patch_module(_subprocess, 'CreateProcess', create_CreateProcessWarnMultiproc)
def exec_rb(self, time, wait, *args):
"""Run rdiff-backup return pid. Wait until done if wait is true"""
arglist = ['python', '../rdiff-backup', '-v3']
if time:
arglist.append("--current-time")
arglist.append(str(time))
arglist.extend(args)
print "Running ", arglist
if wait: return os.spawnvp(os.P_WAIT, 'python', arglist)
else: return os.spawnvp(os.P_NOWAIT, 'python', arglist)
def buildDMG(self):
# Remove DMG if it already exists
if os.path.exists(self.dmgName):
os.unlink(self.dmgName)
createargs = [
'hdiutil', 'create', '-fs', 'HFSX', '-format', 'UDZO',
self.dmgName, '-imagekey', 'zlib-level=9', '-srcfolder',
self.bundleDir, '-volname', self.volume_label
]
if self.applications_shortcut:
scriptargs = [
'osascript', '-e', 'tell application "Finder" to make alias \
file to POSIX file "/Applications" at POSIX file "%s"' %
os.path.realpath(self.buildDir)
]
if os.spawnvp(os.P_WAIT, 'osascript', scriptargs) != 0:
raise OSError('creation of Applications shortcut failed')
createargs.append('-srcfolder')
createargs.append(self.buildDir + '/Applications')
# Create the dmg
if os.spawnvp(os.P_WAIT, 'hdiutil', createargs) != 0:
raise OSError('creation of the dmg failed')
def buildDMG(self):
# remove DMG if it already exists
if os.path.exists(self.dmgName):
os.unlink(self.dmgName)
tmpDir = os.path.join(self.buildDir, 'tmp')
if os.path.exists(tmpDir):
dir_util.remove_tree(tmpDir, verbose=1)
self.mkpath(tmpDir)
# move the app bundle into a separate folder since hdutil copies in the dmg
# the content of the folder specified in the -srcfolder folder parameter, and if we
# specify as input the app bundle itself, its content will be copied and not the bundle
if os.spawnvp(os.P_WAIT, 'cp', ['cp', '-R', self.bundleDir, tmpDir]):
raise OSError('could not move app bundle in staging directory')
createargs = [
'hdiutil', 'create', '-fs', 'HFSX', '-format', 'UDZO',
self.dmgName, '-imagekey', 'zlib-level=9', '-srcfolder',
tmpDir, '-volname', self.volume_label
]
if self.applications_shortcut:
scriptargs = [
'osascript', '-e', 'tell application "Finder" to make alias \
file to POSIX file "/Applications" at POSIX file "%s"' %
os.path.realpath(self.buildDir)
]
if os.spawnvp(os.P_WAIT, 'osascript', scriptargs) != 0:
raise OSError('creation of Applications shortcut failed')
createargs.append('-srcfolder')
createargs.append(self.buildDir + '/Applications')
# create the dmg
if os.spawnvp(os.P_WAIT, 'hdiutil', createargs) != 0:
raise OSError('creation of the dmg failed')
# remove the temporary folder
dir_util.remove_tree(tmpDir, verbose=1)
def wid_specgram(self, event):
import os
args = ['python', 'examples/Boyds/wid_specgram.py']
args += inherited_vars()
# need to pass a string array otherwise treated as array of chars!
args += [str('shot_number=%d' % (self.shot))]
if pyfusion.VERBOSE>5:
print("args to spawn", args)
print("") # so we can see the output
os.spawnvp(os.P_NOWAIT,'python', args)
self.redraw()
def wid_showsigs(self, event):
import os
args = ['python', 'examples/Boyds/wid_showsigs.py']
args += inherited_vars()
# need to pass a string array otherwise treated as array of chars!
args += [str('shot_number=%d' % (self.shot))]
if pyfusion.VERBOSE>5:
print("args to spawn", args)
print("") # so we can see the output
os.spawnvp(os.P_NOWAIT,'python', args)
self.redraw()
#-------- End of class IntegerCtl:
def casalogger(logfile=''):
"""
Spawn a new casalogger using logfile as the filename.
You should only call this if the casalogger dies or you close it
and restart it again.
Note: if you changed the name of the log file using casalog.setlogfile
you will need to respawn casalogger with the new log filename. Eventually,
we will figure out how to signal the casalogger with the new name but not
for a while.
"""
if logfile == '':
if casa.has_key('files') and casa['files'].has_key('logfile') :
logfile = casa['files']['logfile']
else:
casa['files']['logfile'] = os.getcwd( ) + '/casa.log'
logfile = 'casa.log'
pid=9999
if (os.uname()[0]=='Darwin'):
if casa['helpers']['logger'] == 'console':
os.system("open -a console " + logfile)
else:
# XCode7 writes debug messages to stderr, which then end up in the
# Casa console. Hence the stderr is directed to devnull
#pid=os.spawnvp(os.P_NOWAIT,casa['helpers']['logger'],[casa['helpers']['logger'], logfile])
DEVNULL = open(os.devnull, 'w')
pid = Popen([casa['helpers']['logger'],logfile], stderr=DEVNULL).pid
#pid = Popen([casa['helpers']['logger'],logfile], stdin=PIPE, stdout=FNULL, stderr=STDOUT).pid
elif (os.uname()[0]=='Linux'):
pid=os.spawnlp(os.P_NOWAIT,casa['helpers']['logger'],casa['helpers']['logger'],logfile)
else:
print 'Unrecognized OS: No logger available'
if (pid!=9999): logpid.append(pid)
def actualSolve(self, lp):
"""Solve a well formulated lp problem"""
if not self.executable(self.path):
raise PulpSolverError("PuLP: cannot execute "+self.path)
if not self.keepFiles:
pid = os.getpid()
tmpLp = os.path.join(self.tmpDir, "%d-pulp.lp" % pid)
tmpSol = os.path.join(self.tmpDir, "%d-pulp.sol" % pid)
else:
tmpLp = lp.name+"-pulp.lp"
tmpSol = lp.name+"-pulp.sol"
lp.writeLP(tmpLp, writeSOS = 0)
proc = ["glpsol", "--cpxlp", tmpLp, "-o", tmpSol]
if not self.mip: proc.append('--nomip')
proc.extend(self.options)
self.solution_time = clock()
if not self.msg:
proc[0] = self.path
pipe = open(os.devnull, 'w')
if operating_system == 'win':
# Prevent flashing windows if used from a GUI application
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
rc = subprocess.call(proc, stdout = pipe, stderr = pipe,
startupinfo = startupinfo)
else:
rc = subprocess.call(proc, stdout = pipe, stderr = pipe)
if rc:
raise PulpSolverError("PuLP: Error while trying to execute "+self.path)
else:
if os.name != 'nt':
rc = os.spawnvp(os.P_WAIT, self.path, proc)
else:
rc = os.spawnv(os.P_WAIT, self.executable(self.path), proc)
if rc == 127:
raise PulpSolverError("PuLP: Error while trying to execute "+self.path)
self.solution_time += clock()
if not os.path.exists(tmpSol):
raise PulpSolverError("PuLP: Error while executing "+self.path)
lp.status, values = self.readsol(tmpSol)
lp.assignVarsVals(values)
if not self.keepFiles:
try: os.remove(tmpLp)
except: pass
try: os.remove(tmpSol)
except: pass
return lp.status
def patch_new_process_functions():
# os.execl(path, arg0, arg1, ...)
# os.execle(path, arg0, arg1, ..., env)
# os.execlp(file, arg0, arg1, ...)
# os.execlpe(file, arg0, arg1, ..., env)
# os.execv(path, args)
# os.execve(path, args, env)
# os.execvp(file, args)
# os.execvpe(file, args, env)
monkey_patch_os('execl', create_execl)
monkey_patch_os('execle', create_execl)
monkey_patch_os('execlp', create_execl)
monkey_patch_os('execlpe', create_execl)
monkey_patch_os('execv', create_execv)
monkey_patch_os('execve', create_execve)
monkey_patch_os('execvp', create_execv)
monkey_patch_os('execvpe', create_execve)
# os.spawnl(mode, path, ...)
# os.spawnle(mode, path, ..., env)
# os.spawnlp(mode, file, ...)
# os.spawnlpe(mode, file, ..., env)
# os.spawnv(mode, path, args)
# os.spawnve(mode, path, args, env)
# os.spawnvp(mode, file, args)
# os.spawnvpe(mode, file, args, env)
monkey_patch_os('spawnl', create_spawnl)
monkey_patch_os('spawnle', create_spawnl)
monkey_patch_os('spawnlp', create_spawnl)
monkey_patch_os('spawnlpe', create_spawnl)
monkey_patch_os('spawnv', create_spawnv)
monkey_patch_os('spawnve', create_spawnve)
monkey_patch_os('spawnvp', create_spawnv)
monkey_patch_os('spawnvpe', create_spawnve)
if sys.platform != 'win32':
monkey_patch_os('fork', create_fork)
try:
import _posixsubprocess
monkey_patch_module(_posixsubprocess, 'fork_exec', create_fork_exec)
except ImportError:
pass
else:
# Windows
try:
import _subprocess
except ImportError:
import _winapi as _subprocess
monkey_patch_module(_subprocess, 'CreateProcess', create_CreateProcess)
def run(self):
self.run_command('build')
build = self.get_finalized_command('build')
# define the paths within the application bundle
self.bundleDir = os.path.join(build.build_base, self.bundle_name + ".app")
self.contentsDir = os.path.join(self.bundleDir, 'Contents')
self.resourcesDir = os.path.join(self.contentsDir, 'Resources')
self.binDir = os.path.join(self.contentsDir, 'MacOS')
self.frameworksDir = os.path.join(self.contentsDir, 'Frameworks')
# find the executable name
executable = self.distribution.executables[0].targetName
_, self.bundle_executable = os.path.split(executable)
# build the app directory structure
self.mkpath(self.resourcesDir)
self.mkpath(self.binDir)
self.mkpath(self.frameworksDir)
self.copy_tree(BUILD_PATH, self.binDir)
# copy the icon
if self.iconfile:
self.copy_file(self.iconfile, os.path.join(self.resourcesDir, 'icon.icns'))
# copy in Frameworks
for framework in self.include_frameworks:
self.copy_tree(framework, self.frameworksDir + '/' + os.path.basename(framework))
# create the Info.plist file
self.execute(self.create_plist, ())
# make all references to libraries relative
self.execute(self.setRelativeReferencePaths, ())
# for a Qt application, run some tweaks
self.execute(self.prepare_qt_app, ())
# sign the app bundle if a key is specified
if self.codesign_identity:
signargs = ['codesign', '-s', self.codesign_identity]
if self.codesign_entitlements:
signargs.append('--entitlements')
signargs.append(self.codesign_entitlements)
if self.codesign_deep:
signargs.insert(1, '--deep')
if self.codesign_resource_rules:
signargs.insert(1, '--resource-rules=' + self.codesign_resource_rules)
signargs.append(self.bundleDir)
if os.spawnvp(os.P_WAIT, 'codesign', signargs) != 0:
raise OSError('Code signing of app bundle failed')