本文整理汇总了Python中subprocess.Popen.write方法的典型用法代码示例。如果您正苦于以下问题:Python Popen.write方法的具体用法?Python Popen.write怎么用?Python Popen.write使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类subprocess.Popen
的用法示例。
在下文中一共展示了Popen.write方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import write [as 别名]
def run(self):
audio = Popen("aplay", stdin=PIPE).stdin
buffer_increment = 1
t = time()
phase = 0
while not self._halt:
freq = 500 + 500 * (1 - (self.tmp - 21) / 9)
now = time()
while t < now + 0.005:
t = t + 1.0 / 8000
phase = (phase + (freq * 2 * pi / 8000)) % (2 * pi)
audio.write(chr(int(sin(phase) * 50 + 128)))
sleep(0.001)
示例2: set_clipboard
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import write [as 别名]
def set_clipboard(text):
from subprocess import Popen, PIPE
pipe = Popen(['xsel', '--primary --input'], shell=True, stdin=PIPE).stdin
pipe.write(bytes(text, 'ascii'))
pipe.flush()
pipe.close()
示例3: copy_text
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import write [as 别名]
def copy_text(text):
cb_name = get_clipboard_name()
if cb_name is not None:
clipboard = Popen(cb_name, shell=True, stdin=PIPE).stdin
clipboard.write(text)
clipboard.close()
示例4: AMixer
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import write [as 别名]
class AMixer(Thread):
my_vol = 100
def launch_mixer(self,index, cli2=None):
self.index = index
debug("Launch: mixer.py %s '%s'" % (self.index, cli2))
self.mixer_in = Popen(['python', './mixer.py', str(index), cli2 or ''], stdin=subprocess.PIPE).stdin
def set_volume(self, to, taking):
debug2("volume of %s [mixin %s] -> %s in %smsec" % (self.index, self.mixer_in, to, taking))
self.mixer_in.write("%s %s\n" % (to, taking))
def run(self):
debug("Start thread for %s" % self.__class__)
self.launch_mixer(self.my_index)
was = None
while(True):
if was != Attitude.current:
if Attitude.current == self.my_side:
debug2( "On idx %s: %s -> %s" % (self.index, was,Attitude.current))
self.set_volume(self.my_vol,100)
else:
debug2( "Off idx %s: %s -> %s" % (self.index, was,Attitude.current))
self.set_volume(0,100)
was = Attitude.current
time.sleep(0.05)
示例5: create_user
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import write [as 别名]
def create_user(username):
print "Checking for user "+username
p = Popen('id '+username, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
output = p.stdout.read()
if (output[0:3] != "uid"):
# Make the pypo user
print "Creating user "+username
os.system("adduser --system --quiet --group --shell /bin/bash "+username)
#set pypo password
p = os.popen('/usr/bin/passwd pypo 1>/dev/null 2>&1', 'w')
p.write('pypo\n')
p.write('pypo\n')
p.close()
else:
print "User already exists."
#add pypo to audio group
os.system("adduser " + username + " audio 1>/dev/null 2>&1")
#add pypo to www-data group
os.system("adduser " + username + " www-data 1>/dev/null 2>&1")
#add pypo to pulse group
os.system("adduser " + username + " pulse 1>/dev/null 2>&1")
#add pypo to pulse-access group
os.system("adduser " + username + " pulse-access 1>/dev/null 2>&1")
示例6: copy_text
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import write [as 别名]
def copy_text(text):
"""
Copy text to the system clipboard
"""
cb_name = get_clipboard_name()
if cb_name is not None:
clipboard = Popen(cb_name, shell=True, stdin=PIPE).stdin
clipboard.write(text)
clipboard.close()
示例7: __init__
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import write [as 别名]
class AudioPlayer:
song = None
state = States.INITIAL
startup = -1
def __init__(self):
self.mplayer = None
def play(self, song=None):
if self.state == States.INITIAL or self.state == States.STOPPED:
self.song = song
index = configurations.BUFFERED_TEMP_LOCATION + "-" + self.song['artist'].replace(" ", "_") + "-" + self.song['title'].replace(" ", "_")
available = list(glob.glob(index + "*"))
if len(available) > 0:
location = available.pop(0)
else:
stream = pafy.new(song['youtube_link']).getbestaudio()
location = index+"."+stream.extension
stream.download(filepath=location)
self.mplayer = Popen(["mplayer", "-slave", "-really-quiet", location], stdin=PIPE)
self.startup = int(time.time())
self.state = States.PLAYING
elif self.state == States.PAUSED:
self.mplayer.stdin.write(b"p\n")
self.mplayer.stdin.flush()
self.state = States.PLAYING
def pause(self):
self.mplayer.write(b"p\n")
self.mplayer.flush()
self.state = States.PAUSED
def stop(self):
self.mplayer.kill()
self.state = States.STOPPED
def is_dying(self):
return time.time() > (self.song.duration-5+self.startup)
def is_stopped(self):
if self.state == States.STOPPED:
return True
elif self.state == States.INITIAL:
return False
elif self.mplayer.poll() is not None:
self.state = States.STOPPED
return self.state == States.STOPPED
def is_initial(self):
return self.state == States.INITIAL
示例8: get_pubkey
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import write [as 别名]
def get_pubkey(username, projectname, outfile=None):
"""
Retrieves public key for user/project from signer host.
:param outfile: [optional] file to write obtained key
:return: public keys
:raises CoprSignError: failed to retrieve key, see error message
:raises CoprSignNoKeyError: if there are no such user in keyring
"""
usermail = create_gpg_email(username, projectname)
cmd = ["sudo", SIGN_BINARY, "-u", usermail, "-p"]
try:
handle = Popen(cmd, stdout=PIPE, stderr=PIPE)
stdout, stderr = handle.communicate()
except Exception as e:
raise CoprSignError("Failed to get user pubkey"
" due to: {}".format(e))
if handle.returncode != 0:
if "unknown key:" in stderr:
raise CoprSignNoKeyError(
"There are no gpg keys for user {} in keyring".format(username),
return_code=handle.returncode,
cmd=cmd, stdout=stdout, stderr=stderr)
raise CoprSignError(
msg="Failed to get user pubkey\n"
"sign stdout: {}\n sign stderr: {}\n".format(stdout, stderr),
return_code=handle.returncode,
cmd=cmd, stdout=stdout, stderr=stderr)
if outfile:
with open(outfile, "w") as handle:
handle.write(stdout)
return stdout
示例9: feed_xclipboard
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import write [as 别名]
def feed_xclipboard(str):
pipe = Popen("xclip -sel clip", shell=True, stdin=PIPE).stdin
pipe.write(str)
pipe.close()
示例10: Popen
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import write [as 别名]
if '/' in o: options.extend(o.split('/'))
else: options.append(o)
paras[p] = options
elif p in ['cufflinks', 'cuffcompare', 'cuffmerge', 'cuffdiff']:
f = Popen(p, shell=True, stdout=PIPE, stderr=STDOUT).stdout
t = f.readlines()
f.close()
t = filter(lambda(l):len(l)>0, map(lambda(l): l.strip('\n'), t))
opt = map(lambda(l): l.split()[0], filter(lambda(l):l.strip()[0]=='-' and len(l.split())>1, t))
options = []
for o in opt:
if '/' in o: options.extend(o.split('/'))
else: options.append(o)
paras[p] = options
elif p == 'RNA-SeQC':
f = Popen('java -Xmx1g -jar ~/SeqTool/RNA-SeQC/RNA-SeQC_v1.1.4.jar', shell=True, stdout=PIPE, stderr=STDOUT).stdout
t = f.readlines()
f.close()
options = map(lambda(l):l.split()[0], filter(lambda(l):l[0] == '-', map(lambda(l): l.strip(), t)))
paras[p] = options
f = open('AllAvailableParas.txt','w')
for p, opts in paras.iteritems():
f.write('%s'%p)
for o in opts: f.write('\t%s'%o)
f.write('\n')
f.close()
示例11: Popen
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import write [as 别名]
from subprocess import Popen, PIPE
from sys import argv
file1 = argv[1]
file2 = argv[2]
out = argv[3]
f1 = Popen('zcat %s'%file1, shell=True, stdout=PIPE).stdout
f2 = Popen('zcat %s'%file2, shell=True, stdout=PIPE).stdout
o = Popen('gzip - > %s'%out, shell=True, stdin=PIPE).stdin
l = f1.readline()
while l:
o.write('%s'%l)
for i in range(3):
o.write(f1.readline())
for i in range(4):
o.write(f2.readline())
l = f1.readline() #next read?
f1.close()
f2.close()
o.close()
示例12: main
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import write [as 别名]
def main():
# FLANN parameters
# Not current used as OpenCV FLANN is bugged
FLANN_INDEX_KDTREE = 0
index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
search_params = dict(checks=50)
directory = os.getcwd() + "/HSI_Viewer.exe"
pipe = Popen(directory, shell=True, bufsize=100, stdin=PIPE).stdin
doorDetection=0
roll=0
pitch=0
yaw=0
firstTime = True
cap = cv2.VideoCapture(0)
while True:
ret, currentImage = cap.read()
if firstTime:
previousImage = currentImage[:,:]
previousImage = _cleanImage(previousImage)
previousImage = cv2.cvtColor(previousImage,cv2.COLOR_BGR2GRAY)
firstTime = False
continue
currentImage = _cleanImage(currentImage)
currentImage = cv2.cvtColor(currentImage,cv2.COLOR_BGR2GRAY)
# find the keypoints and descriptors with SIFT
sift = cv2.xfeatures2d.SIFT_create()
kp1, des1 = sift.detectAndCompute(currentImage,None)
kp2, des2 = sift.detectAndCompute(previousImage,None)
# Unused FLANN based matcher
matcher = cv2.FlannBasedMatcher(index_params,search_params)
# Currently using a brute force matcher
# matcher = cv2.BFMatcher()
matches = matcher.knnMatch(des1,des2,k=2)
good = []
pts1 = []
pts2 = []
# ratio test as per Lowe's paper
for i,(m,n) in enumerate(matches):
if m.distance < LoweRatio*n.distance:
good.append(m)
pts2.append(kp2[m.trainIdx].pt)
pts1.append(kp1[m.queryIdx].pt)
# Find the fundamental matrix between the first set and second set of points
F, mask = cv2.findFundamentalMat(np.float32(pts1),
np.float32(pts2),cv2.FM_LMEDS)
E = np.dot(np.dot(camera_matrix.T,F),camera_matrix)
np.set_printoptions(formatter={'float': lambda x: "{0:0.3f}".format(x)})
for H_possible in compute_P_from_essential(E):
R = H_possible[:,0:3]
roll_t = atan2(R[2,1],R[2,2])
pitch_t = atan2(-R[2,0],sqrt(R[2,1]**2+R[2,2]**2))
yaw_t = atan2(R[1,0],R[0,0])
t = H_possible[:,3]
if (abs(roll_t) >= np.pi/2 or abs(pitch_t) >= np.pi/2 or
abs(yaw_t) >= np.pi/2):
continue
else:
break
previousImage = currentImage[:,:]
# If we detect a significant change, update our attitude
if (abs(degrees(roll_t)) >= 1 or abs(degrees(pitch_t)) >= 1 or
abs(degrees(yaw_t)) >= 1):
roll = roll + yaw_t
pitch = pitch +roll_t
yaw = yaw + pitch_t
# If there is a large change detected, set attitude back to zero
if (abs(degrees(roll_t)) >= 30 or abs(degrees(pitch_t)) >= 30 or
abs(degrees(yaw_t)) >= 30):
roll = 0
pitch = 0
yaw = 0
os.system('clear')
print "roll: ",degrees(roll)
print "pitch: ",degrees(pitch)
print "yaw: ",degrees(yaw)
pipe.write("%lf %lf %lf"%(roll,pitch,yaw))
cap.release()
示例13: sendmail
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import write [as 别名]
def sendmail(msg):
pipe = Popen("/usr/sbin/sendmail -t", shell=True, stdin=PIPE).stdin
pipe.write(msg.as_string())
pipe.close()
示例14: __init__
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import write [as 别名]
class Pymol:
"""The PyMOL execution object."""
def __init__(self, exec_mode=None):
"""Set up the PyMOL execution object.
@keyword exec_mode: The execution mode which can be either 'module' or 'external'.
@type exec_mode: None or str
"""
# Variable for storing the pymol command history.
self.command_history = ""
# The pymol mode of operation.
self.exec_mode = exec_mode
if not exec_mode:
if dep_check.pymol_module:
self.exec_mode = 'module'
self.open = False
else:
self.exec_mode = 'external'
def clear_history(self):
"""Clear the PyMOL command history."""
self.command_history = ""
def exec_cmd(self, command=None, store_command=True):
"""Execute a PyMOL command.
@param command: The PyMOL command to send into the program.
@type command: str
@param store_command: A flag specifying if the command should be stored in the history
variable.
@type store_command: bool
"""
# Reopen the GUI if needed.
if not self.running():
self.open_gui()
# Execute the command.
if self.exec_mode == 'module':
pymol.cmd.do(command)
else:
self.pymol.write(command + '\n')
# Place the command in the command history.
if store_command:
self.command_history = self.command_history + command + "\n"
def open_gui(self):
"""Open the PyMOL GUI."""
# Use the PyMOL python modules.
if self.exec_mode == 'module':
# Open the GUI.
pymol.finish_launching()
self.open = True
# Otherwise execute PyMOL on the command line.
if self.exec_mode == 'external':
# Test that the PyMOL binary exists.
test_binary('pymol')
# Python 2.3 and earlier.
if Popen == None:
raise RelaxError("The subprocess module is not available in this version of Python.")
# Open PyMOL as a pipe.
self.pymol = Popen(['pymol', '-qpK'], stdin=PIPE).stdin
# Execute the command history.
if len(self.command_history) > 0:
self.exec_cmd(self.command_history, store_command=0)
return
# Test if the PDB file has been loaded.
if hasattr(cdp, 'structure'):
self.open_pdb()
def open_pdb(self):
"""Open the PDB file in PyMOL."""
# Test if PyMOL is running.
if not self.running():
return
# Reinitialise PyMOL.
self.exec_cmd("reinitialize")
# Open the PDB files.
open_files = []
for model in cdp.structure.structural_data:
for mol in model.mol:
# The file path as the current directory.
#.........这里部分代码省略.........
示例15: __init__
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import write [as 别名]
class Molmol:
"""The Molmol execution object."""
def __init__(self):
"""Set up the Molmol execution object."""
# Variable for storing the Molmol command history.
self.command_history = ""
def clear_history(self):
"""Clear the Molmol command history."""
self.command_history = ""
def exec_cmd(self, command=None, store_command=True):
"""Write to the Molmol pipe.
This function is also used to execute a user supplied Molmol command.
@param command: The Molmol command to send into the program.
@type command: str
@param store_command: A flag specifying if the command should be stored in the history
variable.
@type store_command: bool
"""
# Reopen the pipe if needed.
if not self.running():
self.open_gui()
# Write the command to the pipe.
self.molmol.write(command + '\n')
# Place the command in the command history.
if store_command:
self.command_history = self.command_history + command + "\n"
def open_gui(self):
"""Open a Molmol pipe."""
# Test that the Molmol binary exists.
test_binary('molmol')
# Python 2.3 and earlier.
if Popen == None:
raise RelaxError("The subprocess module is not available in this version of Python.")
# Open Molmol as a pipe.
self.molmol = Popen(['molmol', '-f', '-'], stdin=PIPE).stdin
# Execute the command history.
if len(self.command_history) > 0:
self.exec_cmd(self.command_history, store_command=0)
return
# Wait a little while for Molmol to initialise.
sleep(2)
# Test if the PDB file has been loaded.
if hasattr(cdp, 'structure'):
self.open_pdb()
# Run InitAll to remove everything from Molmol.
else:
self.molmol.write("InitAll yes\n")
def open_pdb(self):
"""Open the PDB file in Molmol."""
# Test if Molmol is running.
if not self.running():
return
# Run InitAll to remove everything from molmol.
self.exec_cmd("InitAll yes")
# Open the PDB files.
open_files = []
for model in cdp.structure.structural_data:
for mol in model.mol:
# The file path as the current directory.
file_path = None
if access(mol.file_name, F_OK):
file_path = mol.file_name
# The file path using the relative path.
if file_path == None and hasattr(mol, 'file_path') and mol.file_path != None:
file_path = mol.file_path + sep + mol.file_name
if not access(file_path, F_OK):
file_path = None
# The file path using the absolute path.
if file_path == None and hasattr(mol, 'file_path_abs') and mol.file_path_abs != None:
file_path = mol.file_path_abs + sep + mol.file_name
if not access(file_path, F_OK):
#.........这里部分代码省略.........