Уведомления

Группа в Telegram: @pythonsu

#1 Фев. 15, 2012 23:20:06

iwan_iwanov
От:
Зарегистрирован: 2012-02-15
Сообщения: 4
Репутация: +  0  -
Профиль   Отправить e-mail  

Не запускается Python script в Linux

Ребята, помогите, пожалуйста. Я дама :), в Питоне не разбираюсь, но немного пользуюсь линуксом (Ubuntu 11.10), хотя и не сильна в командной строке (гуглю, когда что-то нужно).

Пытаюсь запустить скрипт, который позволяет конвертировать chm файлы в pdf.

Вот ссылка на архив со скриптом:

http://code.google.com/p/chm2pdf/downloads/detail?name=chm2pdf-0.9.1.tar.gz&can=2&q=

Я скачала архив, разархивировала его и дальше делала все, как указано в README.

Вот что я делала в терминале:


svetlana@svetlana-DOTS:~$ cd Downloads/
svetlana@svetlana-DOTS:~/Downloads$ tar -xzvf chm2pdf-0.9.1.tar.gz
chm2pdf-0.9.1/
chm2pdf-0.9.1/LICENSE
chm2pdf-0.9.1/chm2pdf
chm2pdf-0.9.1/setup.py
chm2pdf-0.9.1/PKG-INFO
chm2pdf-0.9.1/README
svetlana@svetlana-DOTS:~/Downloads$ cd Downloads/chm2pdf-0.9.1
bash: cd: Downloads/chm2pdf-0.9.1: No such file or directory
svetlana@svetlana-DOTS:~/Downloads$ cd /Downloads/chm2pdf-0.9.1/
bash: cd: /Downloads/chm2pdf-0.9.1/: No such file or directory
svetlana@svetlana-DOTS:~/Downloads$ cd chm2pdf-0.9.1/
svetlana@svetlana-DOTS:~/Downloads/chm2pdf-0.9.1$ ls -l
total 144
-rw-r–r– 1 svetlana svetlana 55152 2008-07-09 12:42 chm2pdf
-rw-r–r– 1 svetlana svetlana 55152 2008-07-09 12:42 chm2pdf~
-rw-r–r– 1 svetlana svetlana 18017 2007-07-25 11:58 LICENSE
-rw-r–r– 1 svetlana svetlana 366 2008-07-10 21:34 PKG-INFO
-rw-r–r– 1 svetlana svetlana 914 2008-07-09 12:42 README
-rw-r–r– 1 svetlana svetlana 467 2007-11-18 15:02 setup.py
svetlana@svetlana-DOTS:~/Downloads/chm2pdf-0.9.1$ chmod ugo+x setup.py
svetlana@svetlana-DOTS:~/Downloads/chm2pdf-0.9.1$ ls -l
total 144
-rw-r–r– 1 svetlana svetlana 55152 2008-07-09 12:42 chm2pdf
-rw-r–r– 1 svetlana svetlana 55152 2008-07-09 12:42 chm2pdf~
-rw-r–r– 1 svetlana svetlana 18017 2007-07-25 11:58 LICENSE
-rw-r–r– 1 svetlana svetlana 366 2008-07-10 21:34 PKG-INFO
-rw-r–r– 1 svetlana svetlana 914 2008-07-09 12:42 README
-rwxr-xr-x 1 svetlana svetlana 467 2007-11-18 15:02 setup.py
svetlana@svetlana-DOTS:~/Downloads/chm2pdf-0.9.1$ chmod ugo+x chm2pdf
svetlana@svetlana-DOTS:~/Downloads/chm2pdf-0.9.1$ ls -l
total 144
-rwxr-xr-x 1 svetlana svetlana 55152 2008-07-09 12:42 chm2pdf
-rw-r–r– 1 svetlana svetlana 55152 2008-07-09 12:42 chm2pdf~
-rw-r–r– 1 svetlana svetlana 18017 2007-07-25 11:58 LICENSE
-rw-r–r– 1 svetlana svetlana 366 2008-07-10 21:34 PKG-INFO
-rw-r–r– 1 svetlana svetlana 914 2008-07-09 12:42 README
-rwxr-xr-x 1 svetlana svetlana 467 2007-11-18 15:02 setup.py
svetlana@svetlana-DOTS:~/Downloads/chm2pdf-0.9.1$ python setup.py
usage: setup.py cmd1 [cmd2 …]
or: setup.py –help
or: setup.py –help-commands
or: setup.py cmd –help

error: no commands supplied
svetlana@svetlana-DOTS:~/Downloads/chm2pdf-0.9.1$ python setup.py install
running install
running build
running build_scripts
creating build
creating build/scripts-2.7
copying and adjusting chm2pdf -> build/scripts-2.7
changing mode of build/scripts-2.7/chm2pdf from 664 to 775
running install_scripts
copying build/scripts-2.7/chm2pdf -> /usr/local/bin
error: /usr/local/bin/chm2pdf: Permission denied
svetlana@svetlana-DOTS:~/Downloads/chm2pdf-0.9.1$ ^C
svetlana@svetlana-DOTS:~/Downloads/chm2pdf-0.9.1$



Затем через команду “sudo passwd root” создала корневой пароль и получила корневой доступ. Пыталась запустить в терминале скрипт через команду ./chm2pdf.py и ./chm2pdf - ничего не получается:

захожу в директорию /home/svetlana/Downloads/chm2pdf-0.9.1/ и пытаюсь запустить скрипт оттуда просто нажимая два раза за файле chm2pdf.py. Выскакивает окно с опциями: Run in Terminal, Display, Cancel, Run.

Когда пытаюсь запустить через опцию Run, то ничего вообще не происходит. Когда нажимаю на Run in Terminal, то тут же открывается окно терминала и немедленно закрывается. Что я делаю не так?

Где-то в командной строке (среди множества попыток) выскакивало следующее сообщение:

### See also: http://www.karakas-online.de/forum/viewtopic.php?t=10275
svetlana@svetlana-DOTS:~/Downloads/chm2pdf-0.9.1$ sudo apt-get purge broadcom-sta-common broadcom-sta-source bcmwl-kernel-source

Я пытаюсь установить программы, которые упоминаются,

svetlana@svetlana-DOTS:~/Downloads/chm2pdf-0.9.1$ sudo apt-get purge broadcom-sta-common broadcom-sta-source bcmwl-kernel-source
password for svetlana:
Reading package lists… Done
Building dependency tree
Reading state information… Done
Package bcmwl-kernel-source is not installed, so not removed
Package broadcom-sta-common is not installed, so not removed
Package broadcom-sta-source is not installed, so not removed
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
svetlana@svetlana-DOTS:~/Downloads/chm2pdf-0.9.1$


Питон установлен:

svetlana@svetlana-DOTS:~/Downloads/chm2pdf-0.9.1$ python
Python 2.7.2+ (default, Oct 4 2011, 20:03:08)
on linux2
Type “help”, “copyright”, “credits” or “license” for more information.


И еще, я вообще-то набрела на этот скрипт в одном форуме (http://www.the-ebook.org/forum/viewtopic.php?t=7655&postdays=0&postorder-asc&start=100), где один товарищ написал следующее:

pitman wrote:
Может то, что я сейчас скажу уже баян, но я пользуюсь следующим: http://code.google.com/p/chm2pdf/ .
В командной строке надо набрать (как под виндой - я не знаю):
Code:

chm2pdf –charset cp-1251 –webpage –no-title –no-toc \
–fontsize 12pt –headfootsize 7pt –size 9x11.7cm \
–top 0.2 –bottom 0.2 –left 0.2 –right 0.2 file_name.chm


Кодировка (charset) для каждой книги своя, но обычно cp-1251. Размер шрифта (fontsize) выберите по вкусу. Размеры в данном случае подобраны для PRS-505.

P.S. Таким образом сконвертил не одну книгу. Иногда слетает форматирование на определенном куске текста, но это проблема самого chm.

У меня два вопроса:

1) Почему не запускается мой скрипт, что я делаю не так?

2) Где нужно писать команду, приведенную выше (с форума) - в терминале или в питоновском скрипте? Я вообще-то не очень хорошо представляю, что будет, когда скрипт запустится. Это отдельная программа или он просто что-то делает в терминале?

Буду очень благодарна за помощь, потому что потратила сегодня весь день впустую.

Заранее спасибо,
Светлана



Офлайн

#2 Фев. 16, 2012 11:36:26

Malinaizer
От:
Зарегистрирован: 2009-03-28
Сообщения: 133
Репутация: +  0  -
Профиль   Отправить e-mail  

Не запускается Python script в Linux

в консоле
sudo python /home/svetlana/Downloads/chm2pdf-0.9.1/chm2pdf.py
или так
cd /home/svetlana/Downloads/chm2pdf-0.9.1/
# python chm2pdf.py
и возможно нужно дать права скрипту, почитай про команду chmod!



Отредактировано (Фев. 16, 2012 11:43:29)

Офлайн

#3 Фев. 16, 2012 12:39:47

iwan_iwanov
От:
Зарегистрирован: 2012-02-15
Сообщения: 4
Репутация: +  0  -
Профиль   Отправить e-mail  

Не запускается Python script в Linux

Спасибо за ответ.

chmod я использовала - посмотрите код в предыдущем посту.

То, что вы предлагаете не помогло:


svetlana@svetlana-DOTS:~$ sudo python /home/svetlana/Downloads/chm2pdf-0.9.1/chm2pdf.py
password for svetlana:
python: can't open file ‘/home/svetlana/Downloads/chm2pdf-0.9.1/chm2pdf.py’: No such file or directory
svetlana@svetlana-DOTS:~$ cd Downloads/chm2pdf-0.9.1/
svetlana@svetlana-DOTS:~/Downloads/chm2pdf-0.9.1$ #python chm2pdf.py
svetlana@svetlana-DOTS:~/Downloads/chm2pdf-0.9.1$ ./chm2pdf.py
bash: ./chm2pdf.py: No such file or directory
svetlana@svetlana-DOTS:~/Downloads/chm2pdf-0.9.1$ python chm2pdf.py
python: can't open file ‘chm2pdf.py’: No such file or directory
svetlana@svetlana-DOTS:~/Downloads/chm2pdf-0.9.1$ ./chm2pdf
Usage:
./chm2pdf input_filename

Options:

–beautifulsoup
Correct the HTML code of the pages before converting them to PDF. The BeautifulSoup package (see http://www.crummy.com/software/BeautifulSoup/) needs to be installed.
–bodycolor color
Specifies the background color for all pages.
–bodyfont {courier,helvetica,monospace,sans,serif,times}. Default is times.
–bodyimage filename.{bmp,gif,jpg,png}
–book
Specifies that the HTML sources are structured (headings, chapters, etc.).
–bottom margin{in,cm,mm}
Specifies the bottom margin in points (no suffix or ##pt), inches (##in), centimeters (##cm), or millimeters (##mm).
–browserwidth pixels
See http://www.htmldoc.org/newsgroups.php?ghtmldoc.general+v:3465
–charset {cp-874…1258,iso-8859-1…8859-15,koi8-r}
Specifies the ISO character set to use for the output.
–color
Specifies that PDF output should be in color.
–compression

–continuous
Specifies that the HTML sources are unstructured (plain web pages).
No page breaks are inserted between each file or URL in the output.
–cookies ‘name=“value with space”; name=value’

–datadir directory
Specifies the location of the HTMLDOC data files, usually /usr/share/htmldoc or C:\Program Files\HTMLDOC
–dontextract
If given, ./chm2pdf will not extract the HTML files from the given CHM file, but will use previously extracted copies from the temporary directory (i.e. /tmp/chm2pdf/orig and /tmp/chm2pdf/work). Usually you will use this option after you have used the ‘–extract-only’ option to extract the files in order to correct them manually (in /tmp/chm2pdf/work). After the correction, a call with ‘–dontextract’ will not overwrite your changes, but will use the corrected files instead.
–duplex
Specifies that the output should be formatted for double-sided printing.
–effectduration {0.1..10.0}
Specifies the duration in seconds of PDF page transition effects.
–embedfonts
Specifies that fonts should be embedded in PDF output.
–encryption
Enables encryption of PDF files.
–extract-only
Extract the HTML files from the CHM file and stop.
The extracted files will be found in CHM2PDF_WORK_DIR/input_filename_without_extension.
–firstpage {p1,toc,c1}

–fontsize {4.0..24.0}
Specifies the default font size for body text.
–fontspacing {1.0..3.0}
Specifies the default line spacing for body text.
The line spacing is a multiplier for the font size, so a value of 1.2
will provide an additional 20% of space between the lines.
–footer fff

{–format, -t} {pdf11,pdf12,pdf13,pdf14}
Specifies the output format: pdf11
pdf11 (PDF 1.1/Acrobat 2.0), pdf12 (PDF 1.2/Acrobat 3.0),
pdf or pdf13 (PDF 1.3/Acrobat 4.0), or pdf14 (PDF 1.4/Acrobat 5.0)
–gray

–header fff

–header1 fff

–headfootfont {courier{-bold,-oblique,-boldoblique},
helvetica{-bold,-oblique,-boldoblique},
monospace{-bold,-oblique,-boldoblique},
sans{-bold,-oblique,-boldoblique},
serif{-bold,-italic,-bolditalic},
times{-roman,-bold,-italic,-bolditalic}}
Sets the font to use on headers and footers.
–headfootsize {6.0..24.0}
Sets the size of the font to use on headers and footers.
–headingfont {courier,helvetica,monospace,sans,serif,times}
Sets the typeface to use for headings.
–help
Displays a summary of command-line options.
–hfimage0 filename.{bmp,gif,jpg,png}

–hfimage1 filename.{bmp,gif,jpg,png}

–hfimage2 filename.{bmp,gif,jpg,png}

–hfimage3 filename.{bmp,gif,jpg,png}

–hfimage4 filename.{bmp,gif,jpg,png}

–hfimage5 filename.{bmp,gif,jpg,png}

–hfimage6 filename.{bmp,gif,jpg,png}

–hfimage7 filename.{bmp,gif,jpg,png}

–hfimage8 filename.{bmp,gif,jpg,png}

–hfimage9 filename.{bmp,gif,jpg,png}

–jpeg quality
Sets the JPEG compression level to use for large images. A value of 0 disables JPEG compression.
–landscape

–left margin{in,cm,mm}
Specifies the left margin in points (no suffix or ##pt), inches (##in), centimeters (##cm), or millimeters (##mm).
–linkcolor color
Sets the color of links. You can use well-known color names like blue, or the usual #RRGGBB notation.
–links
Enables generation of links in PDF files (default).
–linkstyle {plain,underline}
Sets the style of links.
–logoimage filename.{bmp,gif,jpg,png}
Specifies an image to be used as a logo in the header or footer in a PDF document.
–logoimage filename.{bmp,gif,jpg,png}
Note that you need to use the –header and/or –footer options with the l parameter.
–no-compression
Disables compression of PDF file.
–no-duplex
Disables double-sided printing.
–no-embedfonts
Specifies that fonts should not be embedded in PDF and PostScript output.
–no-encryption
Disables document encryption.
–no-links
Disables generation of links in a PDF document.
–no-localfiles

–no-numbered
Disables automatic heading numbering.
–no-overflow

–no-strict
Disables strict HTML input checking.
–no-title
Disables generation of a title page.
–no-toc
Disables generation of a table of contents.
–numbered
Numbers all headings in a document.
–nup {1,2,4,6,9,16}
Sets the number of pages that are placed on each output page. Valid values are 1, 2, 4, 6, 9, and 16.
{–outfile, -f} filename{.pdf}
Specifies the name of the output file. If no ending is given, “.pdf” is used.
–overflow

–owner-password password
Sets the owner password for encrypted PDF files.
–pageduration {1.0..60.0}
Sets the view duration of a page in a PDF document.
–pageeffect {none,bi,bo,d,gd,gdr,gr,hb,hsi,hso,vb,vsi,vso,wd,wl,wr,wu}
Specifies the page transition effect for all pages; this attribute is ignored by all Adobe PDF viewers..
–pagelayout {single,one,twoleft,tworight}
Specifies the initial layout of pages for a PDF file.
–pagemode {document,outline,fullscreen}
Specifies the initial viewing mode for a PDF file.
–path “dir1;dir2;dir3;…;dirN”
Specifies a search path for files in a document.
–permissions {all,annotate,copy,modify,print,no-annotate,no-copy,no-modify,no-print,none}
Specifies document permissions for encrypted PDF files. Separate multiple permissions with commas.
–portrait

–prefontsize {4.0..24.0, small, normal, big, huge, +1, +2, -1, -2,…whatever}
Specifies the font size for text inside <pre> tags. Whatever you pass here will be used as font size inside preformatted pieces of text (usually code snippets, console output, program messages…). Effective only together with the ‘–beautifulsoup’ option.
–quiet
Suppresses all messages, even error messages.
–right margin{in,cm,mm}
Specifies the right margin in points (no suffix or ##pt), inches (##in), centimeters (##cm), or millimeters (##mm).
–size {letter,a4,WxH{in,cm,mm},etc}
Specifies the page size using a standard name or in points (no suffix or ##x##pt), inches (##x##in),
centimeters (##x##cm), or millimeters (##x##mm). The standard sizes that are currently recognized
are “letter” (8.5x11in), “legal” (8.5x14in), “a4” (210x297mm), and “universal” (8.27x11in).
–strict
Enables strict HTML input checking.
–textcolor color
Specifies the default color of all text.
–textfont {courier,helvetica,monospace,sans,serif,times}

–title
Enables the generation of a title page.
–titlefile filename.{htm,html,shtml}
Specifies the file to use for the title page. If the file is an image then the title page
is automatically generated using the document meta data and image title.
–titleimage filename.{bmp,gif,jpg,png}
Specifies the image to use for the title page. The title page is automatically
generated using the document meta data and title image.
–tocfooter fff
Sets the page footer to use on table-of-contents pages. See below for the format of fff.
–tocheader fff
Sets the page header to use on table-of-contents pages. See below for the format of fff.
–toclevels levels
Sets the number of levels in the table-of-contents.
–toctitle string
Sets the title for the table-of-contents.
–top margin{in,cm,mm}
Specifies the top margin in points (no suffix or ##pt), inches (##in), centimeters (##cm), or millimeters (##mm).
–user-password password
Specifies the user password for encryption of PDF files.
–verbose
Displays various messages indicating the progress of the conversion process. The verbosity depends on –verbositylevel. If –verbose is not set, almost no messages will be printed. The default is ‘not set’, so if you want the minimum amount of messages, just don' use this option.
–verbositylevel
Specifies the verbosity level of the messages. Can be either ‘low’ or ‘high’. Default is low. The –verbose option must be set, otherwise this option will have no effect.
–version
Displays the current version number.
–webpage
Specifies that the HTML sources are unstructured (plain web pages).
A page break is inserted between each file or URL in the output.

fff
Heading format string; each ‘f’ can be one of:

. = blank
/ = n/N arabic page numbers (1/3, 2/3, 3/3)
: = c/C arabic chapter page numbers (1/2, 2/2, 1/4, 2/4, …)
1 = arabic numbers (1, 2, 3, …)
a = lowercase letters
A = uppercase letters
c = current chapter heading
C = current chapter page number (arabic)
d = current date
D = current date and time
h = current heading
i = lowercase roman numerals
I = uppercase roman numerals
l = logo image
t = title text
T = current time

### See also: http://www.karakas-online.de/forum/viewtopic.php?t=10275

### Either ‘–book’ or ‘–webpage’ or ‘–continuous’ MUST be given!
### Only one of the three options can be present, not two, or even all three of them!
### See above or try ‘./chm2pdf –help | less’ to view the help contents in less.
svetlana@svetlana-DOTS:~/Downloads/chm2pdf-0.9.1$



Отредактировано (Фев. 16, 2012 13:41:09)

Офлайн

#4 Фев. 16, 2012 14:30:03

Malinaizer
От:
Зарегистрирован: 2009-03-28
Сообщения: 133
Репутация: +  0  -
Профиль   Отправить e-mail  

Не запускается Python script в Linux

В архиве есть файл readme там все описанно! как я понял сначало нужно python setup.py install ! Потом
chm2pdf input_filename

где optional это Beautiful Soup, не знаю что это, нозможно dpi(качество) для pdf!
input_filename это имя chm файла
output_filename это имя pdf файла



Отредактировано (Фев. 16, 2012 15:13:05)

Офлайн

#5 Фев. 17, 2012 01:22:59

py.user.next
От:
Зарегистрирован: 2010-04-29
Сообщения: 9978
Репутация: +  857  -
Профиль   Отправить e-mail  

Не запускается Python script в Linux

обычно делаешь
1) python setup.py build
2) python setup.py install
вторую с правами

потом which chm2pdf
потом chm2pdf
прочитай README, там указаны зависимости



Офлайн

#6 Фев. 17, 2012 22:34:17

iwan_iwanov
От:
Зарегистрирован: 2012-02-15
Сообщения: 4
Репутация: +  0  -
Профиль   Отправить e-mail  

Не запускается Python script в Linux

Ребята, спасибо, конечно, за вашу помощь. Но вы забываете, что я полный “ламер”. Я не программист, а пользователь. Все, что вы написали (типа зависимостей) - это китайская грамота для меня. Я вообще ничего не знаю про командную строку - а пользуюсь ей только по такому принципу:

- ага, чтобы установить скрипт в линуксе, мне нужно обладать root privileges. Гуглю: obtain root privileges in Linux и полчаса читаю, что выскакивает в поисковике и что нужно печатать в терминале.

Так что все мои познания - это часы чтения разных сайтов и блогов (под конкретную проблему) и использование метода научного тыка.

Я все делаю, как написано в README файле. Если вам не лень, посмотрите, пожалуйста, код, который я дала в своих предыдущих постах - по-моему, там все написано. То, о чем вы пишете, я уже сделала.

Я установила BeautifulSoup, так что у меня теперь 2 папки в папке Downloads: chm2pdf-0.9.1 и BeautifulSoup-3.2.0. Все делаю, как написано, не работает. Может, я что-то упускаю по незнанию. Но, по аналогии, если человек никогда не видел автомобиль, то сложно ожидать от него, что он покажет, где находится коробка передач.

Если я что-то упустила, то подскажите. Но по принципу:

1) должно быть установлено то-то и то-то;
2) должны быть такие-то и такие-то права к таким файлам / директориям;
3) если выполнено 1 и 2, то в терминале печатай то-то и то-то.

Заранее спасибо и извините за напряг. На свете почти все ламеры ;)



Офлайн

#7 Фев. 18, 2012 03:59:07

py.user.next
От:
Зарегистрирован: 2010-04-29
Сообщения: 9978
Репутация: +  857  -
Профиль   Отправить e-mail  

Не запускается Python script в Linux

1) скачиваешь пакет и распаковываешь его
там файл README, в нём зависимости указаны

Requires:
- python
- chmlib
NOTE: chmlib *must* be configured with ./configure --enable-examples
- pychm
- htmldoc
без них не будет работать этот скрипт
но его можно просто поставить, даже если их нет

2) находясь в распакованной папке, делаешь python setup.py build
появляется папка build
[guest@localhost chm2pdf-0.9.1]$ python setup.py build
running build
running build_scripts
creating build
creating build/scripts-2.7
copying and adjusting chm2pdf -> build/scripts-2.7
changing mode of build/scripts-2.7/chm2pdf from 664 to 775
[guest@localhost chm2pdf-0.9.1]$
3) выполняешь установку
нужны права, чтобы файл мог записаться в папку /usr/bin
sudo python setup.py install
[guest@localhost chm2pdf-0.9.1]$ sudo python setup.py install
[sudo] password for guest:
running install
running build
running build_scripts
running install_scripts
copying build/scripts-2.7/chm2pdf -> /usr/bin
changing mode of /usr/bin/chm2pdf to 775
running install_egg_info
Removing /usr/lib/python2.7/site-packages/chm2pdf-0.9-py2.7.egg-info
Writing /usr/lib/python2.7/site-packages/chm2pdf-0.9-py2.7.egg-info
[guest@localhost chm2pdf-0.9.1]$
4) теперь всё скопировалось в систему
[guest@localhost chm2pdf-0.9.1]$ ls /usr/bin/chm2pdf
/usr/bin/chm2pdf
[guest@localhost chm2pdf-0.9.1]$
запускаешь скрипт
[guest@localhost chm2pdf-0.9.1]$ chm2pdf
Traceback (most recent call last):
File "/usr/bin/chm2pdf", line 24, in <module>
import chm.chm as chm
ImportError: No module named chm.chm
[guest@localhost chm2pdf-0.9.1]$
6) если чего-то не хватает, как у меня, то устанавливаешь эти пакеты, перечисленные в зависимостях



Офлайн

Board footer

Модераторировать

Powered by DjangoBB

Lo-Fi Version