GVKun编程网logo

使用Python的交互式输入/输出(python 交互输入)

38

如果您对使用Python的交互式输入/输出感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于使用Python的交互式输入/输出的详细内容,我们还将为您解答python交互输入的

如果您对使用Python的交互式输入/输出感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于使用Python的交互式输入/输出的详细内容,我们还将为您解答python 交互输入的相关问题,并且为您提供关于C++界面开发框架Qt:Qt for Python 6.0中进一步完善QML + Python的交互、Linux中安装Python的交互式解释器IPython的教程、MongoDB与Python的交互、mysql与python的交互的有价值信息。

本文目录一览:

使用Python的交互式输入/输出(python 交互输入)

使用Python的交互式输入/输出(python 交互输入)

我有一个与用户交互的程序(行为类似于shell),并且我想使用Python子进程模块以交互方式运行它。这意味着,我希望可以写入标准输入并立即从标准输出中获取输出。我尝试了这里提供的许多解决方案,但似乎没有一个适合我的需求。

我编写的代码基于
从Python内部运行交互式命令

import Queue
import threading
import subprocess
def enqueue_output(out,queue):
    for line in iter(out.readline,b''):
        queue.put(line)
    out.close()

def getOutput(outQueue):
    outStr = ''
    try:
        while True: # Adds output from the queue until it is empty
            outStr += outQueue.get_nowait()

    except Queue.Empty:
        return outStr

p = subprocess.Popen("./a.out",stdin=subprocess.PIPE,stout=subprocess.PIPE,stderr=subprocess.PIPE,bufsize = 1)
#p = subprocess.Popen("./a.out",shell=False,universal_newlines=True)

outQueue = Queue()
errQueue = Queue()

outThread = Thread(target=enqueue_output,args=(p.stdout,outQueue))
errThread = Thread(target=enqueue_output,args=(p.stderr,errQueue))

outThread.daemon = True
errThread.daemon = True

outThread.start()
errThread.start()

p.stdin.write("1\n")
p.stdin.flush()
errors = getOutput(errQueue)
output = getOutput(outQueue)

p.stdin.write("5\n")
p.stdin.flush()
erros = getOutput(errQueue)
output = getOutput(outQueue)

问题是队列保持为空,就像没有输出一样。仅当我将标准程序需要执行和终止的所有输入都写到标准输入中时,我才得到输出(这不是我想要的)。例如,如果我做类似的事情:

p.stdin.write("1\n5\n")
errors = getOutput(errQueue)
output = getOutput(outQueue)

有什么方法可以做我想做的事吗?


该脚本将在Linux机器上运行。我更改了脚本,并删除了Universal_newlines = True
+将bufsize设置为1,并在写入后立即刷新了标准输入。我仍然没有任何输出。

第二次尝试:

我尝试了此解决方案,它对我有用:

from subprocess import Popen,PIPE

fw = open("tmpout","wb")
fr = open("tmpout","r")
p = Popen("./a.out",stdin = PIPE,stdout = fw,stderr = fw,bufsize = 1)
p.stdin.write("1\n")
out = fr.read()
p.stdin.write("5\n")
out = fr.read()
fw.close()
fr.close()

C++界面开发框架Qt:Qt for Python 6.0中进一步完善QML + Python的交互

C++界面开发框架Qt:Qt for Python 6.0中进一步完善QML + Python的交互

Qt是一个跨平台框架,通常用作图形工具包,它不仅创建CLI应用程序中非常有用。而且它也可以在三种主要的台式机操作系统以及移动操作系统(如Symbian,Nokia Belle,Meego Harmattan,MeeGo或BB10)以及嵌入式设备,Android(Necessitas)和iOS的端口上运行。现在我们为你提供了免费的试用版。赶快前往慧都网免费下载把>>

自从PySide植到Qt5又名PySide2)的初始端口以来,由于QML的普及,我们希望在绑定集中完全支持QML的交互。

在第一个正式发行版5.12中,涵盖了QML和Python交互的许多用例,但还是忽略了社区真正需要的几个用例。现在我们正在开发Qt6的新功能和改进,我们希望解决其中的大多数问题。

在这里,您可以找到我们到目前为止计划在Python 6.0 Qt中所要完成的功能的摘要。

无限制类型

以前最多可以注册50个自定义类型的限制在6.0中消失了,现在您可以根据需要注册任意多个类型

单例类型

从6.0开始,您可以使用qmlRegisterSingletonType注册用于QML的自定义单例

例如,如果您想向QML公开有关操作系统的信息,则可以创建以下类:

class SystemInfo(QObject): def __init__(self): QObject.__init__(self) def getOSName(self): return platform.system() def getOSRelease(self): return platform.release() osName = Property(str, getOSName) osRelease = Property(str, getOSRelease)

然后在CustomType1.0 下注册:

qmlRegisterSingletonType(SystemInfo, "CustomType", 1, 0, "SystemInfo")

现在,您SystemInfo只需导入CustomTypeQML代码即可访问:

import CustomType 1.0 Text { text: "OS Name: " + SystemInfo.osName }

不可创建的类型

另一个缺少的功能是将自定义QML类型注册为不可创建的选项,这可以通过qmlRegisterUncreatableType来实现。

您可以使用它,例如在QML中注册自定义enum类

class Theme(QObject): @QEnum class Variant(Enum): Default, Dark, HighContrast = range(3) # ... qmlRegisterUncreatableType(Theme, "CustomType", 1, 0, "Theme", "Theme can''t be created")

注册后,您可以这样使用enum:

import QtQuick 2.0 import CustomType 1.0 Item { property int theme: Theme.Default }

适应新的类注册方式

Qt for Python现在还支持QmlElement decorator模式,该decorator的工作方式与QML_ELEMENTC ++ 类似。

QML_IMPORT_NAME = "com.library.name" QML_IMPORT_MAJOR_VERSION = 1 QML_IMPORT_MINOR_VERSION = 0 # Optional @QmlElement class ClassForQml(QObject): # ...

例如,此代码段将公开ClassForQml给QML,并且可以通过全局变量中指定的导入名称和版本来导入。如果您要注册许多类型,这对您可能特别有用。

结论

我们了解到QML + Python交互的其他方面可能是您的应用程序当前需要的,你或者会从中受益。因此,我希望您的一些意见建议,甚至是有关如何实现Qt forPython的创新,对于基于QML的应用程序而言,这是一个非常好重要的部分。

如果这篇文章没能满足你的需求、可前往慧都网获取更多文章教程!

Linux中安装Python的交互式解释器IPython的教程

Linux中安装Python的交互式解释器IPython的教程

IPython是Python的交互式Shell,提供了代码自动补完,自动缩进,高亮显示,执行Shell命令等非常有用的特性。特别是它的代码补完功能,例如:在输入zlib.之后按下Tab键,IPython会列出zlib模块下所有的属性、方法和类。完全可以取代自带的bash

下面介绍下linux安装IPython四种方法:

第一种:ipython源码安装
ipython的源码下载页面为:https://pypi.python.org/pypi/ipython

或者是到git页面下载:https://github.com/ipython/ipython/downloads
假设我们下载的文件名为:ipython-0.8.2.tar.gz

#tar zvxf ipython-0.8.2.tar.gz  //解压文件
#cd ipython-0.8.2 //进入刚刚解压的文件夹内

进入文件加后会看到一个setup.py的安装脚本,运行以下命令进行安装

#python setup.py install

操作将会在site-packages目录中安装ipyhon的库文件,并在scripts目录中创建一个ipython脚本。在unix系统中,该目录与python的二进制文件目录相同。如果系统中已经安装了python包,则ipython将会安装在/usr/bin目录下。

第二种:通过系统的软件包管理器安装ipython软件包。
如.deb包可以在debian和ubuntu上获取,直接用以下命令:

#apt-get install ipython  
//ubuntu将ipython的库文件安装到/usr/share/python-support/ipython目录下,包括一系列.pth文件和符号链接,而ipython的二进制文件则安装在/usr/bin/ipyton目录下。

 redhat(centos)使用下面的命令:

#yum list | grep ipython  //查看你所使用的yum源是否有ipython包,没有的话,就只能换源或者源码安装了,国内貌似都没有

#yum install ipython.noarch  //安装ipython

或者是通过rpm包安装,命令如下:

#rpm -ivh https://dl.fedoraproject.org/pub/epel/6/x86_64/ipython-0.10-3.el6.noarch.rpm

第三种:通过python包进行安装。
在python包中包含了ipython。将python包解压后,可以看到一个扩展名为.egg的文件。Egg文件可以通过easy_install工具安装。  easy_install工具可以检查egg文件的配置,然后选择需要安装的内容。easy_install工具通过python包的索引(python package index,简称PyPI,又被称作python cheeseshop)确定包的安装。使用easy_install工具安装ipython,只需要用户对site_package目录有写权限,直接运行

#easy_install ipython

Ps:前提是你已经安装了easy_install工具,所以你如果想用这种方法来安装,就要先安装setuptools才能用easy_install工具。

第四种:直接不安装就用.
下载ipython的源码后,运行ipython.py安装命令后,就可以使用该下载版本中的ipython实例了。这种方法能够使site-packages目录保持简明,但同时也会带来一些问题,那就是如果没有解压ipython,也就没有修改PYTHONPATH环境变量,ipython将不能作为一个库文件直接使用。

我个人建议还是源码安装吧

有问题的可以去官方查看安装文档教程:

http://ipython.org/ipython-doc/stable/install/install.html

http://ipython.org/install.html


PS:出现gcc: readline/libreadline.a报错
ipython这个工具非常好用,不过在linux下安装的时候却报了下面2个错。(环境是centos6.2,python2.7)

gcc: readline/libreadline.a: No such file or directory
gcc: readline/libhistory.a: No such file or directory

解决:
只需要

yum -y install readline-devel
yum -y install patch
pip install ipython

即可

MongoDB与Python的交互

MongoDB与Python的交互

驱动模块

  • pymongo是python里常用的操作MongoDB的驱动模块
  • 可用pip下载安装
 pip install pymongo

创建连接

  • MongoClient是MongoDB的客户端代理对象,可以用来执行增删改查操作,而且还内置了连接池
 from pymongo import MongoClient
 client = MongoClient(host="localhost",port=27017)
 client.admin.authenticate("admin","123456")

数据写入

  • insert_one和insert_many两个函数可向MongoDB写入数据
 client.school.student.insert_one({"name":"alex"})
 client.school.student.insert_many({"name":"bob"},{"name":"cindy"})

数据查询

  • find_one和find两个函数可从MmongDB中查询数据
 student = client.school.student.find_one({"name":"alex"})
 print(student)
 students = client.school.student.find({})
 for one in students:
    print(one["_id"],one["name"])
  • skip:用于数据分类查询
  • limit:用于数据分页查询
 students = client.school.student.find({}).skip(0).limit(10)
  • count_documents:查询记录总数
 count = client.school.student.count_documents({})
  • distinct:查询不重复的字段
 students = client.school.student.distinct("name")
  • sort:对查询结果进行排序
 students = client.school.student.find().sort([("name",-1)])

数据修改

  • update_one和update_many两个函数可以修改MongoDB数据
 client.school.student.update_one({"name":"alex"},{"$set":{"sex":"女"}})
 client.school.student.update_many({},{"$set":{"grade":"七年级"}})

数据删除

  • delete_one和delete_many两个函数可以删除MongoDB数据
 client.school.student.delete_one({"name":"alex"})
 client.school.student.delete_many({})

存储文件

连接GridFS

  • GridFS是MongoDB的文件存储方案,主要用于存储超过16M的文件
from gridfs import GridFS
db = client.school
gfs = GridFS(db,collection="book")

保存文件

  • put函数可把文件保存到GridFS中
file = open("D:/Python编程:从入门到实践.pdf","rb")
args = {"type":"PDF","keyword":"Python"}
gfs.put(file,file="Python编程:从入门到实践.PDF",**args)
file.close()

查找文件

  • find_one和find函数可以查找GridFS中存储的文件
book = gfs.find_one({"filename":"Python编程:从入门到实践.PDF"})
print(book.keywode)
books = gfs.find({"type":"PDF"})
for one in books:
   print(one.filename)

判断是否存储了文件

  • exists可判断GridFS是否存储了某个文件
rs = gfs.exists({"filename":"Python编程:从入门到实践.PDF"})
print(rs)

读取文件

  • get函数可以从GfridFS中读取文件,并且只能通过主键读取
from bson.objectid import ObjectId
book = gfs.find_one({"filename":"Python编程:从入门到实践.PDF"})
id = book._id
document = gfs.get(ObjectId(id))
file = open("D:/Python从入门到实践.PDF","wb")
file.write(document.read())
file.close()

删除文件

  • delect函数可以从GridFS中删除文件,同样只能通过主键删除(先查找到文件的主键)
from bson.objectid import ObjectId
book = gfs.find_one({"filename":"Python编程:从入门到实践.PDF"})
id = book._id
gfs.delete(ObjectId(id))

mysql与python的交互

mysql与python的交互

##导包
import pymysql

#封装方法
def main():
    #创建mysql连接
    conn = pymysql.connect(host=''localhost'',port=3306,database=''python01'',user=''root'',password=''858362'',charset=''utf8'')
    #创建cursor,接受mysql语句并且执行的对象方法
    cursor = conn.cursor()
    #插入10万数据
    for x in range(100000):
        cursor.execute("insert into test_index values(''ha - %s'',''ca - %s'')"%(x,x))
    conn.commit()

if __name__ == ''__main__'':
    main()
import pymysql

def test():
    conn=pymysql.connect(host=''localhost'',port=3306,database=''message'',user=''root'',password=''858362'',charset=''utf8'')
    cursor=conn.cursor()

    cursor.execute(''select * from classify'')

    ret=cursor.fetchall()
    print(ret)
    cursor.execute(''select * from news where id = 1'')
    r=cursor.fetchone()
    print(r)
    cursor.execute(''delete from news where id = 2'')
    cursor.execute(''select * from news'')
    e=cursor.fetchall()
    print(e)
    cursor.execute(''update news set name = "张三" where id = 3'')
    cursor.execute(''select * from news where id = 3'')
    a=cursor.fetchone()
    print(a)
    cursor.execute(''select * from news where s_news = 1'')
    vv=cursor.fetchall()
    print(vv)
    cursor.execute(''select * from news where (count>5 and is_delete = "是")'')
    ew=cursor.fetchone()
    print(ew)
    conn.commit()
    cursor.close()
    conn.close()

if __name__ == ''__main__'':
    test()
import pymysql
#
# #创建函数
def main():
    #建立mysql连接
    conn = pymysql.connect(host=''127.0.0.1'',port=3306,user=''root'',password=''858362'',database=''python01'',charset=''utf8'')
    #创建cursor对象,执行sql语句,声明游标对象返回dict
    cursor=conn.cursor(cursor=pymysql.cursors.DictCursor)

    cursor.execute("select * from students")#select * from students
    ret=cursor.fetchone()
    # ret=cursor.fetchall()
    # print(ret)
    # print(ret[4])
    # print(ret[4][''name''])
    print(ret[''name''])
    cursor.close()
    conn.close()
if __name__ == ''__main__'':
    main()

 

我们今天的关于使用Python的交互式输入/输出python 交互输入的分享已经告一段落,感谢您的关注,如果您想了解更多关于C++界面开发框架Qt:Qt for Python 6.0中进一步完善QML + Python的交互、Linux中安装Python的交互式解释器IPython的教程、MongoDB与Python的交互、mysql与python的交互的相关信息,请在本站查询。

本文标签: