我正在使用子进程模块启动子进程并连接到它的输出流(stdout).我希望能够在其标准输出上执行非阻塞读取.有没有办法让.readline非阻塞或在我调用之前检查流上是否有数据.readline?我希望这是可移植的,或至少在Windows和Linux下工作.
这是我现在如何做到的(.readline如果没有数据可用,则阻止它):
p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE)
output_str = p.stdout.readline()
Run Code Online (Sandbox Code Playgroud) 注意:这个问题最初是在这里被问到的,但即使没有找到可接受的答案,赏金时间也已过期.我正在重新询问这个问题,包括原始问题中提供的所有细节.
python脚本使用sched模块每60秒运行一组类函数:
# sc is a sched.scheduler instance
sc.enter(60, 1, self.doChecks, (sc, False))
Run Code Online (Sandbox Code Playgroud)
该脚本使用此处的代码作为守护进程运行.
作为doChecks的一部分调用的许多类方法使用子进程模块来调用系统函数以获取系统统计信息:
ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
Run Code Online (Sandbox Code Playgroud)
这可以在整个脚本崩溃之前运行一段时间,并出现以下错误:
File "/home/admin/sd-agent/checks.py", line 436, in getProcesses
File "/usr/lib/python2.4/subprocess.py", line 533, in __init__
File "/usr/lib/python2.4/subprocess.py", line 835, in _get_handles
OSError: [Errno 12] Cannot allocate memory
Run Code Online (Sandbox Code Playgroud)
脚本崩溃后,服务器上的free -m输出为:
$ free -m
total used free shared buffers cached
Mem: 894 345 549 0 0 0
-/+ buffers/cache: 345 549
Swap: 0 …Run Code Online (Sandbox Code Playgroud) 我正在尝试编写一个小脚本来在每次执行脚本时挂载VirtualBox共享文件夹.我想用Python做,因为我正在尝试用它来学习脚本.
问题是我需要权限才能启动mount命令.我可以将脚本作为sudo运行,但我更喜欢它自己创建sudo.
我已经知道将密码写入.py文件是不安全的,但我们谈的是一个根本不重要的虚拟机:我只想点击.py脚本并让它运行起来.
这是我的尝试:
#!/usr/bin/env python
import subprocess
sudoPassword = 'mypass'
command = 'mount -t vboxsf myfolder /home/myuser/myfolder'
subprocess.Popen('sudo -S' , shell=True,stdout=subprocess.PIPE)
subprocess.Popen(sudoPassword , shell=True,stdout=subprocess.PIPE)
subprocess.Popen(command , shell=True,stdout=subprocess.PIPE)
Run Code Online (Sandbox Code Playgroud)
我的python版本是2.6
我正在使用Python 2.6中的GUI前端,通常它非常简单:您使用subprocess.call()或subprocess.Popen()发出命令并等待它完成或对错误做出反应.如果您的程序停止并等待用户交互,您会怎么做?例如,程序可能会停止并询问用户是否有ID和密码或如何处理错误?
c:\> parrot
Military Macaw - OK
Sun Conure - OK
African Grey - OK
Norwegian Blue - Customer complaint!
(r) he's Resting, (h) [Hit cage] he moved, (p) he's Pining for the fjords
Run Code Online (Sandbox Code Playgroud)
到目前为止,我所阅读的所有内容都告诉您如何在程序完成后才读取程序的所有输出,而不是在程序运行时如何处理输出.我无法安装新模块(这是一个LiveCD),我将不止一次处理用户输入.
我正在尝试为Minecraft服务器编写处理程序/控制器.我的问题是,我似乎无法通过写作和阅读来正常工作.当客户端发出使用服务器类方法的命令时,serverComMinecraft服务器的文本/日志开始进入Python窗口/ Python控制台,并且连接的客户端挂起.此外,似乎在我使用之后Popen,Minecraft服务器在我写入服务器(aka serverCom方法)之前并没有真正启动.如果有人想知道,则Popen转到打开.jar文件的批处理文件.这是在Windows XP上.
import subprocess
import os
import configobj
import socket
import threading
from time import sleep
config = configobj.ConfigObj("config.ini")
cHost = config["hostip"]
cPort = int(config["hostport"])
cBuffer = int(config["serverbuffer"])
cClients = int(config["numberofclients"])
cPassword = config["password"]
class server(object):
def __init__(self):
self.process = False
self.folder = "C:\\servers\\minecraft-danny"
self.max = configobj.ConfigObj("%s\\simpleserver.properties"%self.folder)["maxPlayers"]
def serverStart(self):
if not self.process:
self.process = subprocess.Popen("java -Xmx1024m -Xms1024m -jar minecraft_server.jar nogui", cBuffer, None, subprocess.PIPE, subprocess.PIPE, subprocess.STDOUT, cwd = self.folder)
return True
return …Run Code Online (Sandbox Code Playgroud) 我需要做这样的帖子,但是我需要创建一个可以给出输入并多次输出的子进程.该帖子的接受答案有良好的代码......
from subprocess import Popen, PIPE, STDOUT
p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
grep_stdout = p.communicate(input=b'one\ntwo\nthree\nfour\nfive\nsix\n')[0]
print(grep_stdout.decode())
# four
# five
Run Code Online (Sandbox Code Playgroud)
......我想继续这样:
grep_stdout2 = p.communicate(input=b'spam\neggs\nfrench fries\nbacon\nspam\nspam\n')[0]
print(grep_stdout2.decode())
# french fries
Run Code Online (Sandbox Code Playgroud)
但是,我得到以下错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/subprocess.py", line 928, in communicate
raise ValueError("Cannot send input after starting communication")
ValueError: Cannot send input after starting communication
Run Code Online (Sandbox Code Playgroud)
如果我理解正确的话,proc.stdin.write()方法不能让你收集输出.什么是保持线路开放以进行持续输入/输出的最简单方法?
编辑:====================
它看起来像是pexpect一个有用的库,我正在尝试做什么,但我无法让它工作.这是对我实际任务的更完整的解释.我hfst用来获得个别(俄语)单词的语法分析.以下演示了它在bash shell中的行为:
$ hfst-lookup analyser-gt-desc.hfstol
> ?????
????? ?????+N+Neu+Inan+Sg+Acc …Run Code Online (Sandbox Code Playgroud) 我在使用子进程模块重定向另一个程序的stdio时遇到问题.只是从stdout读取导致挂起,并且Popen.communicate()可以工作,但它在读/写后关闭管道.实现这个最简单的方法是什么?
我在Windows上玩这个:
import subprocess
proc = subprocess.Popen('python -c "while True: print \'Hi %s!\' % raw_input()"',
shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
while True:
proc.stdin.write('world\n')
proc_read = proc.stdout.readline()
if proc_read:
print proc_readRun Code Online (Sandbox Code Playgroud) 我正在将一个bash脚本移植到python 2.6,并想要替换一些代码:
cat $( ls -tr xyz_`date +%F`_*.log ) | filter args > bzip2
Run Code Online (Sandbox Code Playgroud)
我想我想要一些类似于http://docs.python.org/release/2.6/library/subprocess.html上的"替换shell管道"示例,ala ...
p1 = Popen(["filter", "args"], stdin=*?WHAT?*, stdout=PIPE)
p2 = Popen(["bzip2"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]
Run Code Online (Sandbox Code Playgroud)
但是,我不确定如何最好地提供它p1的stdin值,以便它连接输入文件.似乎我可以添加......
p0 = Popen(["cat", "file1", "file2"...], stdout=PIPE)
p1 = ... stdin=p0.stdout ...
Run Code Online (Sandbox Code Playgroud)
...但这似乎超越了使用(缓慢,低效)管道来调用具有重要功能的外部程序.(任何体面的shell都会在cat内部执行.)
所以,我可以设想一个满足文件对象API要求的自定义类,因此可以用于p1的stdin,连接任意其他文件对象.(编辑:现有答案解释了为什么这是不可能的)
难道蟒蛇2.6有一个机制,解决这方面的需要/想,或其他可能Popen对cat在Python界被认为是完美的罚款?
谢谢.
我有一个主进程,我运行一个子进程,stdin是我想要管道的.我知道我可以使用文件来做到这一点:
import subprocess
subprocess.call('shell command', stdin=open('somefile','mode'))
Run Code Online (Sandbox Code Playgroud)
有没有选项使用自定义标准输入管道没有实际的硬盘驱动器文件?有没有选项,例如,使用字符串列表(每个列表元素将是换行符)?
我知道python子进程调用.readline()管道对象.
我需要编写一个Python脚本,它可以运行另一个命令行程序并与它的stdin和stdout流进行交互.本质上,Python脚本将从目标命令行程序读取,通过写入其stdin进行智能响应,然后再次从程序中读取结果.(它会反复这样做.)
我已经查看了子进程模块,我似乎无法让它执行我正在寻找的读/写/读/写操作.还有什么我应该尝试的吗?