[英]Printing a calendar via Python. Code is not working =/
我正在用Python开发一个小程序(PyGTK),可以打印出用户输入的日历(格里高利语)。
这是我的代码:
#!/usr/bin/env python
import pygtk, gtk, subprocess
pygtk.require("2.0")
class Base:
def printing(self, widget):
text = self.textbox.get_text()
printingit = "cal -y %s | lpr" % (text)
process = subprocess.Popen(printingit.split(), stdout=subprocess.PIPE)
output = process.communicate()[0]
def __init__(self):
self.win = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.win.set_position(gtk.WIN_POS_CENTER)
self.win.set_size_request(350, 200)
self.win.set_resizable(False)
self.win.set_title("Calendar")
self.win.connect('destroy',lambda w: gtk.main_quit())
self.textbox = gtk.Entry()
self.textbox.set_size_request(70, 30)
self.lable = gtk.Label("Year:")
self.button = gtk.Button("Print")
self.button.set_size_request(60, 45)
self.button.connect("clicked", self.printing)
box = gtk.Fixed()
box.put(self.lable, 160, 25)
box.put(self.textbox, 140, 40)
box.put(self.button, 145, 100)
self.win.add(box)
self.win.show_all()
def main(self):
gtk.main()
if __name__ == "__main__":
base = Base()
base.main()
实际打印命令cal -y %s | lpr % (text)
时不起作用cal -y %s | lpr % (text)
cal -y %s | lpr % (text)
。 我已经做到了,所以它将文本框的文本替换为应该获得的最终命令,并且将其更改为我希望的值cal -y 2015 | lpr
cal -y 2015 | lpr
。 我只是尝试将其放入终端机,并且像往常一样工作,这让我很困惑!
我在终端中运行了程序,这是我尝试打印时收到的消息:
Usage: cal [general options] [-hjy] [[month] year]
cal [general options] [-hj] [-m month] [year]
ncal [general options] [-bhJjpwySM] [-s country_code] [[month] year]
ncal [general options] [-bhJeoSM] [year]
General options: [-NC3] [-A months] [-B months]
For debug the highlighting: [-H yyyy-mm-dd] [-d yyyy-mm]
如果有人知道为什么会这样,我将非常感谢! 预先谢谢你= D
如果要在命令中使用shell语法(管道),则需要将命令作为字符串传递给Popen
构造函数,而不是作为列表传递。 而且您必须使用shell=True
:
output = subprocess.check_output(printingit, shell=True)
否则,执行的命令将与以下命令相同:
cal '-y' 'text' '|' 'lpr'
但是,当您从文本字段获取输入的一部分时,您不应直接将其传递给shell。
或者,您可以自己创建管道:
lpr = subprocess.Popen('lpr', stdin=subprocess.PIPE, stdout=subprocess.PIPE)
process = subprocess.Popen(['cal', '-y', text], stdout=lpr.stdin)
output = lpr.communicate()
process.wait()
顺便说一句,您可以使用calendar
模块来代替使用子流程来调用cal
。 cal -y 2012
功能与calendar.calendar(2014)
相同,因此您可以将代码替换为:
cal = calendar.calendar(int(text))
process = subprocess.Popen(['lpr'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
output = process.communicate(cal) # cal.encode(locale.getpreferredencoding(False)) for python3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.