매뉴얼:Pywikibot/PAWS

From mediawiki.org
This page is a translated version of the page Manual:Pywikibot/PAWS and the translation is 81% complete.
Outdated translations are marked like this.
더 자세한 사항은 Wikitech:PAWS에서 확인하세요.

이 문서는 PAWS(Pywikibot: A Web Shell)를 이용하여 위키미디어 클라우드 서비스의 노트북을 이용한 Pywikibot 의 빠른 대화형 개요를 제공합니다.

PAWS 터미널은 크로미움 기반의 브라우저에서만 복사 및 붙여넣기를 지원합니다. (구글 크롬, 오페라, 사파리와 새로운 마이크로소프트 엣지는 괜찮습니다.) 만일 다른 브라우저를 사용하고 있다면, 우클릭 메뉴를 사용하거나 이 연습문에서 언급된 명령어를 수동으로 입력해야 합니다. 내용 안에 명령어가 들어있는 bash 파일을 만들거나 단말기 내에 bash file.sh를 호출할 수도 있습니다.
경고 경고: PAWS 안의 모든 노트북과 터미널은 공지 없이 중단될 수 있습니다. 만일 당신의 작업이 몇 시간 이상 걸리신다면 다른 장소(툴포지 등)를 사용하시는 것을 강하게 추천드립니다.

위키미디어 계정 만들기

이 과정을 빠르게 지나가려면 위키백과 또는 위키미디어에 계정이 있어야 합니다. 특수:계정만들기로 하나 만드세요.

계정을 만든 후에는, https://test.wikipedia.org/ 에 들려서 자신이 만든 계정이 브라우저 오른쪽 최상단에 나타나는지 확인해주세요. (이것은 작업 T120327 근처에서 동작합니다.)

위키미디어의 새 사용자라면 그 계정으로 메타, 위키미디어, 위키백과, 위키데이터, 위키미디어 공용 등을 한 번씩 들러주세요. 그리고 맨 위에 있는 메시지를 모두 읽고 지우세요.

노트북으로 접속하기

노트북에서 진행을 시작하려면, https://hub-paws.wmcloud.org/hub 로 가세요.

‘Sign in with MediaWiki’를 클릭하고 나서 ‘OAuth 이용 인증’에 동의하는지 물어볼 때 ‘허용합니다’를 클릭합니다. PAWS에 처음 접속하려면, 서버 생성이 필요합니다. 초록색 ‘Start my Server’ 버튼을 클릭합니다. 새로운 서버가 시작되려면 몇 분 정도 기다리는 것이 보통입니다.

완료되었다면, https://paws.wmflabs.org/paws/user/<username>/tree처럼 URL에다가 넘겨주기가 됩니다.

단말기 시작하기

새로운 대화형 단말기를 시작하기 위해,

  1. $paws에 가서
  2. File > New > Terminal을 클릭하세요

이러면 새 창에 리눅스 ‘$’ 프롬프트가 열립니다.

이 단말기는 모방기가 아닙니다. 실제 배시 셀도커 용기에 있는 실제 리눅스 설치의 일부분으로, 그렇기에 어떠한 배시 명령어든 쓸 수 있고, 또한 설치한 리눅스에서 사용가능한 어떠한 명령어도 쓸 수 있습니다.

사용 가능한 일부 명령어를 보려면, ls /bin/.을 쓰세요.

$ ls /bin/
bash         cat            domainname  journalctl  mkdir          pwd         stty                            tar           zcmp
unzip2       chacl          echo        kill        mknod          rbash       su                              tempfile      zdiff
../..
$ ls /usr/bin/
2to3-3.4                 dvipdf                     lcf                         printf               systemd-path                         
X11                      dwp                        ld                          prlimit              systemd-run
../..

To see them all, press TAB twice.


위키에 로그인하기

이는 서버 내에 계정이 만들어질 것이고 명령줄에서 로그인이 허가됩니다. 아래의 명령어는 연습위키에 접속할 수 있음을 보여줍니다. OAuth를 이용한다면, 비밀번호를 입력할 필요가 없습니다.

$ pwb.py login
Logging in to wikipedia:test as <username>
Logged in on wikipedia:test as <username>.

$HOME 디렉토리(/home/paws) 내에 ‘user-config.py’라는 이름의 파일을 만들고 ‘mylang ’ 및 ‘family’ 변수를 추가한다면 pywikibot에서 다른 위키로 연결할 수 있습니다:

mylang = 'test'
family = 'wikipedia'

You can type vim user-config.py in the terminal, then I to insert text, add the text, then Esc to exist insert mode, then :wq and Enter to finishing editing.


문서 만들기

문서를 만들려면, 단말기에 사용자 이름과 ‘<username>’을 대신하여 아래의 명령어를 입력하고, 바뀜을 즉시 수락하려면 ‘Y’를 누르세요.

$ pwb.py add_text -up -talk -page:"User talk:<username>" -text:"Hello. ~~~~"
Loading User talk:<username>...

>>> User talk:<username> <<<
@@ -0,0 +1 @@
+ Hello. ~~~~

Do you want to accept these changes? ([Y]es, [N]o, [a]ll, open in [b]rowser): Y
Page [[User talk:<username>]] saved

위키를 편집했습니다. 웹 브라우저 상에서 https://test.wikipedia.org/wiki/User_talk:<username>를 열어 바뀜을 봅시다.

‘-help’ 명령줄 옵션과 이러한 명령줄 스크립트 각각에 대해 자세히 볼 수 있습니다.

$ pwb.py add_text -help
...

문서 꺼내오기

많은 문서를 가져오는 것은 ‘listpages’ 명령어로 합니다.

이전 문단에서 만들었던 문서의 내용을 가져오려면, 다음 명령어를 입력하세요:

$ pwb.py listpages -page:"User talk:<username>" -save
   1 <username>
Saving User talk:<username> to /home/paws/User_talk_<username>
1 page(s) found

이제 $ ls을 실행하면 저장된 문서가 나타납니다.

실제 스크립트 예시

위키백과 상에서 사용된 웹사이트가 URL를 바꾼다면 위키백과 상의 해당 링크는 낡게 되고, 만일 웹사이트가 오래된 URL에서 새 URL로 넘겨주기되지 않았다면 깨진 링크가 될 수도 있습니다. 예시로, 브리태니커 백과사전이 링크를 다음과 같이 바꾸었습니다: http://www.britannica.com/EBchecked/media/를 http://www.britannica.com/topic/[topic name]/images-videos/*로 이동했습니다. 당신은 낡은 URL을 사용하는 영어 위키백과 문서의 목록을 w:Special:LinkSearch/http://www.britannica.com/EBchecked/media에서 찾을 수 있습니다. 이 모든 링크를 업데이트 시키는 건 상당한 시간이 걸릴 겁니다. 다행히도, 브리태니커 백과사전이 낡은 URL에서 새로운 URL로 리다이렉트 시켜주었기 때문에 임의적으로 고쳐질 필요는 없습니다.

간단한 예로는, 영어 위키백과는 최근 http://www.britannica.com/EBchecked/ 대신에 http://britannica.com/EBchecked/ 링크를 포함하고 있습니다. 즉, ‘www.’ 하위 도메인은 URL 상에서 사라집니다.

최근 영어 위키백과에는 15건의 사례가 있습니다.

다른 언어로 된 위키백과 또한 이러한 문제를 지니고 있습니다. 가령, 독일어 위키백과 상에 1건의 사례가 있습니다.

이 링크를 고치기 위해, 우리는 Pywikibot replace.py 스크립트를 사용할 수 있습니다. 이 견본에서 우리는 영어 위키백과의 자동 편집에 대한 엄격한 규칙이 있으므로, 위키에 작성하는 것을 막기 위해 ‘-simulate’ 인수를 사용할 것입니다.

먼저 http://britannica.com/EBchecked/에 연결된 모든 문서를 나열하세요.

$ pwb.py listpages -lang:en -weblink:"britannica.com/EBchecked/"
   1 Bhatner fort
   2 Mohammad Ishaq Khan
   3 Fringe theories/Noticeboard/Archive 7
   4 El Riego phase
   5 Catalonia/Archive 4
   6 Stephen I of Hungary
   7 Stephen I of Hungary/Archive 1
   8 Väinö Tanner
   9 Tokaji
  10 Transylvania/Archive5
  11 Hungarians in Romania
  12 Transylvania
  13 Uttarakhand
  14 Françoise Giroud
14 page(s) found

이제 우리는 이 문서들이 실제로 문서 내에 실질적인 URL을 가지고 있는지 확인합니다. 즉, 여기에는 틀은 사용하고 있지 않습니다.

$ pwb.py listpages -lang:en -weblink:"britannica.com/EBchecked/" -grep:"britannica.com\/EBchecked"
   1 Bhatner fort
   2 Mohammad Ishaq Khan
   3 Fringe theories/Noticeboard/Archive 7
   4 El Riego phase
   5 Catalonia/Archive 4
   6 Stephen I of Hungary
   7 Stephen I of Hungary/Archive 1
   8 Väinö Tanner
   9 Tokaji
  10 Transylvania/Archive5
  11 Hungarians in Romania
  12 Transylvania
  13 Uttarakhand
  14 Françoise Giroud
14 page(s) found

이제 ‘replace’를 사용하여 빠진 ‘www.’를 추가하세요.

$ pwb.py replace -lang:en -simulate -weblink:"britannica.com/EBchecked/" -grep:"britannica.com\/EBchecked" "http://britannica.com/EBchecked/" "http://www.britannica.com/EBchecked/"
The summary message for the command line replacements will be something like: Bot: Automated text replacement  (-http://britannica.com/EBchecked/ +http://www.britannica.com/EBchecked/)
Press Enter to use this automatic message, or enter a description of the
changes your bot will make: 
Logging in to wikipedia:en as <username>
Retrieving 14 pages from wikipedia:en.
Retrieving 14 pages from wikipedia:en.


>>> Stephen I of Hungary <<<
@@ -47 +47 @@
- Stephen's birth date is uncertain because it was not recorded in contemporaneous documents.{{sfn|Györffy|1994|p=64}} Hungarian and Polish chronicles written centuries later give three different years: 967, 969 and 975.{{sfn|Kristó|2001|p=15}} The unanimous testimony of his three late 11th-century or early 12th-century [[hagiographies]] and other Hungarian sources, which state that Stephen was "still an adolescent" in 997,<ref>''Hartvic, Life of King Stephen of Hungary'' (ch. 5), p. 381.</ref> substantiate the reliability of the later year (975).{{sfn|Györffy|1994|p=64}}{{sfn|Kristó|2001|p=15}} Stephen's ''[[Life of Saint Stephen, King of Hungary (Vita minor)|Lesser Legend]]'' adds that he was born in [[Esztergom]],{{sfn|Györffy|1994|p=64}}{{sfn|Kristó|2001|p=15}}<ref name=Britannica>{{cite encyclopedia|title=Stephen I|url=http://britannica.com/EBchecked/topic/565415/Stephen-I|encyclopedia=[[Encyclopædia Britannica]]|publisher=Encyclopædia Britannica, Inc.|year=2008|accessdate=2008-07-29}}</ref> which implies that he was born after 972 because his father, [[Géza, Grand Prince of the Hungarians]], chose Esztergom as royal residence around that year.{{sfn|Györffy|1994|p=64}} Géza promoted the spread of Christianity among his subjects by force, but never ceased worshipping pagan gods.{{sfn|Kontler|1999|p=51}}{{sfn|Berend|Laszlovszky|Szakács|2007|p=331}} Both his son's ''[[Life of Saint Stephen, King of Hungary (Vita maior)|Greater Legend]]'' and the nearly contemporaneous [[Thietmar of Merseburg]] described Géza as a cruel monarch, suggesting that he was a despot who mercilessly consolidated his authority over the rebellious Hungarian lords.{{sfn|Berend|Laszlovszky|Szakács|2007|p=331}}{{sfn|Bakay|1999|p=547}}
+ Stephen's birth date is uncertain because it was not recorded in contemporaneous documents.{{sfn|Györffy|1994|p=64}} Hungarian and Polish chronicles written centuries later give three different years: 967, 969 and 975.{{sfn|Kristó|2001|p=15}} The unanimous testimony of his three late 11th-century or early 12th-century [[hagiographies]] and other Hungarian sources, which state that Stephen was "still an adolescent" in 997,<ref>''Hartvic, Life of King Stephen of Hungary'' (ch. 5), p. 381.</ref> substantiate the reliability of the later year (975).{{sfn|Györffy|1994|p=64}}{{sfn|Kristó|2001|p=15}} Stephen's ''[[Life of Saint Stephen, King of Hungary (Vita minor)|Lesser Legend]]'' adds that he was born in [[Esztergom]],{{sfn|Györffy|1994|p=64}}{{sfn|Kristó|2001|p=15}}<ref name=Britannica>{{cite encyclopedia|title=Stephen I|url=http://www.britannica.com/EBchecked/topic/565415/Stephen-I|encyclopedia=[[Encyclopædia Britannica]]|publisher=Encyclopædia Britannica, Inc.|year=2008|accessdate=2008-07-29}}</ref> which implies that he was born after 972 because his father, [[Géza, Grand Prince of the Hungarians]], chose Esztergom as royal residence around that year.{{sfn|Györffy|1994|p=64}} Géza promoted the spread of Christianity among his subjects by force, but never ceased worshipping pagan gods.{{sfn|Kontler|1999|p=51}}{{sfn|Berend|Laszlovszky|Szakács|2007|p=331}} Both his son's ''[[Life of Saint Stephen, King of Hungary (Vita maior)|Greater Legend]]'' and the nearly contemporaneous [[Thietmar of Merseburg]] described Géza as a cruel monarch, suggesting that he was a despot who mercilessly consolidated his authority over the rebellious Hungarian lords.{{sfn|Berend|Laszlovszky|Szakács|2007|p=331}}{{sfn|Bakay|1999|p=547}}

Do you want to accept these changes? ([y]es, [N]o, [e]dit, open in [b]rowser, [a]ll, [q]uit): N

...

PAWS 및 색상을 지원하는 단말기에서 바뀜의 차이는 초록색 글자로 ‘www.’가 추가되어 보여질 것이고, 이는 제안된 바뀜을 찾기 쉽게 만들 것입니다.

Pywikibot 내부

경고 경고: 파일은 공개되므로, 서버의 파일 안에 비밀번호를 적지 마세요!

다음은 PAWS 파이썬의 시즌을 사용합니다.

  1. PAWS 홈에 가서
  2. ‘New’를 오른쪽 버튼으로 클릭하고
  3. ‘Python 3’을 선택합니다.

이러면 새로운 창이 열립니다.

텍스트 박스 안에 아래의 명령문을 적고 Cell 메뉴에서 'Run'을 클릭하거나 shift+enter를 누르세요.

import pywikibot

새 텍스트 박스가 밑에 생길 겁니다. 아래의 명령문을 통해 https://test.wikipedia.org/ 와 연결된 새 APISite 항목을 만드세요.

site = pywikibot.Site('test', 'wikipedia')

Describe "site" by entering it into the new text box and selecting "Run".

site

It should show

 Out[3]: APISite("test", "wikipedia")

Create a page object:

page = pywikibot.Page(site, 'test')

Check it exists by running:

page.exists()

It should output

 VERBOSE:pywiki:Found 1 wikipedia:test processes running, including this one.
 Out[5]: True

Show the text on the page:

page.text

Change the page text in the object:

page.text = 'Hello world'

Save the page to the wiki:

page.save()

The response should be:

Page [[Test]] saved
INFO:pywiki:Page [[Test]] saved

The interactive Python 3 notebook allows many lines to be run together. The above could be put into one text box and Run

import pywikibot

site = pywikibot.Site('test', 'wikipedia')
page = pywikibot.Page(site, 'test')

page.text = 'Hello world!'
page.save()

The log of your interactive Python session can be saved or downloaded for future reference.

PAWS 내 온라인 문서에 접근하기

Pywikibot documentation may be found at https://doc.wikimedia.org/pywikibot/. It is primarily sourced from docstrings, which can be loaded in the interactive Python 3 notebook using the Python built-in function help().

For example, to look at the arguments for the save method above, run either:

help(page.save)

또는

help(pywikibot.Page.save)

Pywikibot 스크립트 편집하기

Pywikibot 라이브러리 및 스크립트는 /srv/paws에 위치하고 있으며, 읽기 전용입니다. 설치된 Pywikibot 라이브러리는 PAWS 내에서 수정할 수 없습니다.

스크립트는 내 PAWS 홈으로 복사한 후 수정해야 합니다.

예를 들어, 수정된 "checkimages.py"를 실행하려면:

터미널 안에서 cp /srv/paws/pwb/scripts/checkimages.py ~를 입력합니다. 브라우저 안에서 [$paws PAWS 홈]에 가서 checkimages.py를 클릭합니다. 브라우저 안에서 파일을 수정할 수 있습니다. 코드를 수정하세요. 가령, 1775번째 줄의 start = time.time() 코드 뒤에 새 1776번째 줄에 당신의 이름을 추가합니다: print("MYNAME's version.")

  1. 편집 인터페이스의 파일 메뉴에서 저장을 눌러 편집본을 저장합니다.
  2. 터미널 안에서 pwb.py ~/checkimages.py -simulate -limit:10를 입력합니다. (If no '-limit:x' defined, the program would run until all images checked, it may take long time.)

같이 보기


If you need more help on setting up your Pywikibot visit the #pywikibot IRC channel connect or pywikibot@ mailing list.