2015-01-13 112 views
-4

我寫了一個簡單的命令行轉換爲Linux用戶,使用python2.x,蟒蛇 - 3.x的支持

,但它不支持python3,代碼少於100行,

main.py

#!/usr/bin/env python2 
# entry of program, 

import sys 
import urllib2 
from BeautifulSoup import BeautifulSoup 
import ConfigParser 
from os.path import expanduser 

version = "v0.1" + " beta3" 

# read config 
googleDomain = "google.com" 
targetLang = "en" 
srcLang = "auto" 

home = expanduser("~") 
config = ConfigParser.RawConfigParser() 
config.read(home + "/.config/pygtrans/config.ini") 

if config.has_option("basic","google_domain"): 
    tmpDomain = config.get("basic", "google_domain") 
    if tmpDomain and (not tmpDomain.isspace()): 
     googleDomain = tmpDomain 

if config.has_option("basic","target_language"): 
    tmpTargetLang = config.get("basic", "target_language") 
    if tmpTargetLang and (not tmpTargetLang.isspace()): 
     targetLang = tmpTargetLang 

if config.has_option("basic","source_language"): 
    tmpSrcLang = config.get("basic", "source_language") 
    if tmpSrcLang and (not tmpSrcLang.isspace()): 
     srcLang = tmpSrcLang 

## param check 
key = "" 
if len(sys.argv) < 2: 
    print("Please use following formats:\n\t%s" % ("gtrans <input_string> [<target_language>] [<source_language>]")) 
    print("\t%s" % ("gtrans (-v | -version)")) 
    print("Common languages:\n\t%s\n" % ("en, zh, zh_TW, ja, fr, de,")) 
    sys.exit(1) 
elif sys.argv[1]=="-v" or sys.argv[1]=="--version": 
    print "pygtrans - " + version 
    sys.exit(0) 
else: 
    key = sys.argv[1] 
    if len(sys.argv) >=3: 
     targetLang = sys.argv[2] 
    if len(sys.argv) >=4: 
     srcLang = sys.argv[3] 

## http request 
resultId = "result_box" 
userAgent = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36" 
headers = {'User-Agent':userAgent} 
url = "http://translate." + googleDomain + "/?langpair=" + srcLang + "|" + targetLang + "&text=" + key 
page = urllib2.urlopen(urllib2.Request(url, None, headers)) 

## result parse 
soup = BeautifulSoup(page) 
x = soup.body.find(id=resultId).text 
print unicode(key, 'utf-8') + "\t->\t" + x 

任何一個可以指出其功能與python3.x問題?或有興趣幫助解決它在github上?


@Update:

嘗試1小時後,我感到非常的Python版本和lib版本dispointed,我用幾乎每一個解放運動在版本問題,很多功能也給起來......這不像編程。

+0

@Cyber​​壓痕問題解決。 –

+0

@Cyber​​是正確的:在Py3中,'print'是一個函數(不是語句),所以它需要被**調用**(在'print'之後的括號中)。 –

+1

只需使用['2to3'](https://docs.python.org/2/library/2to3.html)工具... – Bakuriu

回答

1

最大的問題是

print "some string" 

現在必須

也出現了changes to the urllib module

+2

@EricWang在文件的頂部添加'from __future__ import print_function',你也可以在python2中使用'print'作爲函數。 – Bakuriu