0
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pygmentsを、標準入出力で使う

Last updated at Posted at 2016-10-01

Pygmentsでpython→HTML

Pygmentsで、syntaxhighlightされたpythonコードを、htmlで出力して、サイトに貼り付けるやり方をいまだにやっております。(現在、markdown記法のブログ投稿ツールを探しています。)

Pygmentsを使ってhtmlを出すには、大きく分けて、2パターンあると思います。
1 .pyファイルを、.htmlファイルに出力するやり方。
2 標準入出力を使うやり方。
主に、2のやり方を、Ubuntuの端末から行ってきましたが、同じことがWindowsですぐにできませんでした。
理由は、Windowsの標準入力から抜け出す方法を知らなかったからというだけでした。

とりあえず、嵌ったので書きます。

1 .pyファイルを、.htmlファイルに出力するやり方

Pythonのコードを保存(例えば、a.py)

pygmentize -f html -l python noclasses=True -o a.html a.py
```↓
a.htmlをテキストエディタで開いてコピペ
## 2 標準入出力を使うやり方。
入力ファイルがない場合に標準入力入力待ちになります
長いコードの一部分をコピペhighlightしたhtmlを取得したい時など便利だと思っています
### Windowsのコマンドラインからの場合
```pygmentize -f html -l python -O noclasses=True
```↓
標準入力にpythonのコード書く

**改行Ctrl+ZEnterで標準入力から抜ける**

標準出力に表示されるのをコピペ

**Ctrl+CでもCtrl+Breakでもでない。)**
### Ubuntuの端末からの場合
```pygmentize -f html -l python -O noclasses=True
```↓
標準入力にpythonのコード書く

**Ctrl+Dで標準入力から抜ける**

標準出力に表示されるのをコピペ
## コマンドの意味
>```pygmentize -f html -l python noclasses=True -o a.html a.py```もしくは
```pygmentize -l python -f html -O noclasses=True```と書きましたが

```-l python``` …………………………lexer字句解析python用のを使う元のファイルがpythonの時はpythonと書くしrubyのときはrubyと書き換える
```-f html``` ………………………………出力するフォーマットはhtml
```-O noclasses=True``` これがあるとcssいじらなくてもよくなる代わりに毎回htmlタグに色指定が入り編集時にごちゃごちゃする

### -oは、-Oとは違う。(大文字小文字で意味が違う。)
[公式サイトから引用](http://pygments.org/docs/cmdline/)
>The -o option gives an output file name. If it is not given, output is written to stdout.
>>-oオプションは出力ファイル名を与えますもし与えられなかったら出力はstdout標準出力に書かれます


```-o hogehoge.html``` 有る無しで、「指定されたファイルを読むファイルが出力されるとなるか標準出力に表示される端末画面に表示されるかが決まるようです
# 本当は4パターン
```-f html -l python noclasses=True```は省略します

```pygments -o a.html a.py ``` a.pyを読んでa.htmlに出力
```pygments a.py``` a.pyを読んでcmdもしくは端末画面に表示標準出力に出力
```pygments -o a.html``` 入力待ち標準入力)→入力終了改行Ctrl+ZEnterもしくはCtrl+D)→a.htmlに出力
```pygments``` 入力待ち入力終了cmdもしくは端末画面に表示
0
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?