util.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. import os
  2. import re
  3. import sys
  4. import time
  5. import json
  6. import signal
  7. from urllib.request import urlopen
  8. from urllib.parse import urlparse
  9. from decimal import Decimal
  10. from urllib.parse import quote
  11. from datetime import datetime
  12. from subprocess import TimeoutExpired, Popen, PIPE, DEVNULL, CompletedProcess, CalledProcessError
  13. from multiprocessing import Process
  14. from config import (
  15. IS_TTY,
  16. OUTPUT_PERMISSIONS,
  17. REPO_DIR,
  18. SOURCES_DIR,
  19. OUTPUT_DIR,
  20. ARCHIVE_DIR,
  21. TIMEOUT,
  22. TERM_WIDTH,
  23. SHOW_PROGRESS,
  24. ANSI,
  25. CHROME_BINARY,
  26. FETCH_WGET,
  27. FETCH_PDF,
  28. FETCH_SCREENSHOT,
  29. FETCH_DOM,
  30. FETCH_FAVICON,
  31. FETCH_TITLE,
  32. FETCH_MEDIA,
  33. SUBMIT_ARCHIVE_DOT_ORG,
  34. )
  35. # URL helpers: https://docs.python.org/3/library/urllib.parse.html#url-parsing
  36. scheme = lambda url: urlparse(url).scheme
  37. without_scheme = lambda url: urlparse(url)._replace(scheme='').geturl().strip('//')
  38. without_query = lambda url: urlparse(url)._replace(query='').geturl().strip('//')
  39. without_fragment = lambda url: urlparse(url)._replace(fragment='').geturl().strip('//')
  40. without_path = lambda url: urlparse(url)._replace(path='', fragment='', query='').geturl().strip('//')
  41. path = lambda url: urlparse(url).path
  42. basename = lambda url: urlparse(url).path.rsplit('/', 1)[-1]
  43. domain = lambda url: urlparse(url).netloc
  44. query = lambda url: urlparse(url).query
  45. fragment = lambda url: urlparse(url).fragment
  46. extension = lambda url: basename(url).rsplit('.', 1)[-1].lower() if '.' in basename(url) else ''
  47. base_url = lambda url: without_scheme(url) # uniq base url used to dedupe links
  48. short_ts = lambda ts: ts.split('.')[0]
  49. URL_REGEX = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))[^<\""]+'
  50. HTML_TITLE_REGEX = '<title>(.[^<>]+)'
  51. def check_dependencies():
  52. """Check that all necessary dependencies are installed, and have valid versions"""
  53. python_vers = float('{}.{}'.format(sys.version_info.major, sys.version_info.minor))
  54. if python_vers < 3.5:
  55. print('{}[X] Python version is not new enough: {} (>3.5 is required){}'.format(ANSI['red'], python_vers, ANSI['reset']))
  56. print(' See https://github.com/pirate/ArchiveBox#troubleshooting for help upgrading your Python installation.')
  57. raise SystemExit(1)
  58. if FETCH_PDF or FETCH_SCREENSHOT or FETCH_DOM:
  59. if run(['which', CHROME_BINARY], stdout=DEVNULL).returncode:
  60. print('{}[X] Missing dependency: {}{}'.format(ANSI['red'], CHROME_BINARY, ANSI['reset']))
  61. print(' Run ./setup.sh, then confirm it was installed with: {} --version'.format(CHROME_BINARY))
  62. print(' See https://github.com/pirate/ArchiveBox for help.')
  63. raise SystemExit(1)
  64. # parse chrome --version e.g. Google Chrome 61.0.3114.0 canary / Chromium 59.0.3029.110 built on Ubuntu, running on Ubuntu 16.04
  65. try:
  66. result = run([CHROME_BINARY, '--version'], stdout=PIPE)
  67. version_str = result.stdout.decode('utf-8')
  68. version_lines = re.sub("(Google Chrome|Chromium) (\\d+?)\\.(\\d+?)\\.(\\d+?).*?$", "\\2", version_str).split('\n')
  69. version = [l for l in version_lines if l.isdigit()][-1]
  70. if int(version) < 59:
  71. print(version_lines)
  72. print('{red}[X] Chrome version must be 59 or greater for headless PDF, screenshot, and DOM saving{reset}'.format(**ANSI))
  73. print(' See https://github.com/pirate/ArchiveBox for help.')
  74. raise SystemExit(1)
  75. except (IndexError, TypeError, OSError):
  76. print('{red}[X] Failed to parse Chrome version, is it installed properly?{reset}'.format(**ANSI))
  77. print(' Run ./setup.sh, then confirm it was installed with: {} --version'.format(CHROME_BINARY))
  78. print(' See https://github.com/pirate/ArchiveBox for help.')
  79. raise SystemExit(1)
  80. if FETCH_WGET:
  81. if run(['which', 'wget'], stdout=DEVNULL).returncode or run(['wget', '--version'], stdout=DEVNULL).returncode:
  82. print('{red}[X] Missing dependency: wget{reset}'.format(**ANSI))
  83. print(' Run ./setup.sh, then confirm it was installed with: {} --version'.format('wget'))
  84. print(' See https://github.com/pirate/ArchiveBox for help.')
  85. raise SystemExit(1)
  86. if FETCH_FAVICON or SUBMIT_ARCHIVE_DOT_ORG:
  87. if run(['which', 'curl'], stdout=DEVNULL).returncode or run(['curl', '--version'], stdout=DEVNULL).returncode:
  88. print('{red}[X] Missing dependency: curl{reset}'.format(**ANSI))
  89. print(' Run ./setup.sh, then confirm it was installed with: {} --version'.format('curl'))
  90. print(' See https://github.com/pirate/ArchiveBox for help.')
  91. raise SystemExit(1)
  92. if FETCH_MEDIA:
  93. if run(['which', 'youtube-dl'], stdout=DEVNULL).returncode or run(['youtube-dl', '--version'], stdout=DEVNULL).returncode:
  94. print('{red}[X] Missing dependency: youtube-dl{reset}'.format(**ANSI))
  95. print(' Run ./setup.sh, then confirm it was installed with: {} --version'.format('youtube-dl'))
  96. print(' See https://github.com/pirate/ArchiveBox for help.')
  97. raise SystemExit(1)
  98. def chmod_file(path, cwd='.', permissions=OUTPUT_PERMISSIONS, timeout=30):
  99. """chmod -R <permissions> <cwd>/<path>"""
  100. if not os.path.exists(os.path.join(cwd, path)):
  101. raise Exception('Failed to chmod: {} does not exist (did the previous step fail?)'.format(path))
  102. chmod_result = run(['chmod', '-R', permissions, path], cwd=cwd, stdout=DEVNULL, stderr=PIPE, timeout=timeout)
  103. if chmod_result.returncode == 1:
  104. print(' ', chmod_result.stderr.decode())
  105. raise Exception('Failed to chmod {}/{}'.format(cwd, path))
  106. def progress(seconds=TIMEOUT, prefix=''):
  107. """Show a (subprocess-controlled) progress bar with a <seconds> timeout,
  108. returns end() function to instantly finish the progress
  109. """
  110. if not SHOW_PROGRESS:
  111. return lambda: None
  112. def progress_bar(seconds, prefix):
  113. """show timer in the form of progress bar, with percentage and seconds remaining"""
  114. chunk = '█' if sys.stdout.encoding == 'UTF-8' else '#'
  115. chunks = TERM_WIDTH - len(prefix) - 20 # number of progress chunks to show (aka max bar width)
  116. try:
  117. for s in range(seconds * chunks):
  118. progress = s / chunks / seconds * 100
  119. bar_width = round(progress/(100/chunks))
  120. # ████████████████████ 0.9% (1/60sec)
  121. sys.stdout.write('\r{0}{1}{2}{3} {4}% ({5}/{6}sec)'.format(
  122. prefix,
  123. ANSI['green'],
  124. (chunk * bar_width).ljust(chunks),
  125. ANSI['reset'],
  126. round(progress, 1),
  127. round(s/chunks),
  128. seconds,
  129. ))
  130. sys.stdout.flush()
  131. time.sleep(1 / chunks)
  132. # ██████████████████████████████████ 100.0% (60/60sec)
  133. sys.stdout.write('\r{0}{1}{2}{3} {4}% ({5}/{6}sec)\n'.format(
  134. prefix,
  135. ANSI['red'],
  136. chunk * chunks,
  137. ANSI['reset'],
  138. 100.0,
  139. seconds,
  140. seconds,
  141. ))
  142. sys.stdout.flush()
  143. except KeyboardInterrupt:
  144. print()
  145. pass
  146. p = Process(target=progress_bar, args=(seconds, prefix))
  147. p.start()
  148. def end():
  149. """immediately finish progress and clear the progressbar line"""
  150. # protect from double termination
  151. #if p is None or not hasattr(p, 'kill'):
  152. # return
  153. nonlocal p
  154. if p is not None:
  155. p.terminate()
  156. p = None
  157. sys.stdout.write('\r{}{}\r'.format((' ' * TERM_WIDTH), ANSI['reset'])) # clear whole terminal line
  158. sys.stdout.flush()
  159. return end
  160. def pretty_path(path):
  161. """convert paths like .../ArchiveBox/archivebox/../output/abc into output/abc"""
  162. return path.replace(REPO_DIR + '/', '')
  163. def save_source(raw_text):
  164. if not os.path.exists(SOURCES_DIR):
  165. os.makedirs(SOURCES_DIR)
  166. ts = str(datetime.now().timestamp()).split('.', 1)[0]
  167. source_path = os.path.join(SOURCES_DIR, '{}-{}.txt'.format('stdin', ts))
  168. with open(source_path, 'w', encoding='utf-8') as f:
  169. f.write(raw_text)
  170. return source_path
  171. def download_url(url):
  172. """download a given url's content into downloads/domain.txt"""
  173. if not os.path.exists(SOURCES_DIR):
  174. os.makedirs(SOURCES_DIR)
  175. ts = str(datetime.now().timestamp()).split('.', 1)[0]
  176. source_path = os.path.join(SOURCES_DIR, '{}-{}.txt'.format(domain(url), ts))
  177. print('[*] [{}] Downloading {} > {}'.format(
  178. datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
  179. url,
  180. pretty_path(source_path),
  181. ))
  182. end = progress(TIMEOUT, prefix=' ')
  183. try:
  184. downloaded_xml = urlopen(url).read().decode('utf-8')
  185. end()
  186. except Exception as e:
  187. end()
  188. print('[!] Failed to download {}\n'.format(url))
  189. print(' ', e)
  190. raise SystemExit(1)
  191. with open(source_path, 'w', encoding='utf-8') as f:
  192. f.write(downloaded_xml)
  193. return source_path
  194. def fetch_page_title(url, timeout=10, progress=SHOW_PROGRESS):
  195. """Attempt to guess a page's title by downloading the html"""
  196. if not FETCH_TITLE:
  197. return None
  198. try:
  199. if progress:
  200. sys.stdout.write('.')
  201. sys.stdout.flush()
  202. html_content = urlopen(url, timeout=timeout).read().decode('utf-8')
  203. match = re.search(HTML_TITLE_REGEX, html_content)
  204. return match.group(1).strip() if match else None
  205. except Exception:
  206. return None
  207. def str_between(string, start, end=None):
  208. """(<abc>12345</def>, <abc>, </def>) -> 12345"""
  209. content = string.split(start, 1)[-1]
  210. if end is not None:
  211. content = content.rsplit(end, 1)[0]
  212. return content
  213. def get_link_type(link):
  214. """Certain types of links need to be handled specially, this figures out when that's the case"""
  215. if link['base_url'].endswith('.pdf'):
  216. return 'PDF'
  217. elif link['base_url'].rsplit('.', 1) in ('pdf', 'png', 'jpg', 'jpeg', 'svg', 'bmp', 'gif', 'tiff', 'webp'):
  218. return 'image'
  219. elif 'wikipedia.org' in link['domain']:
  220. return 'wiki'
  221. elif 'youtube.com' in link['domain']:
  222. return 'youtube'
  223. elif 'soundcloud.com' in link['domain']:
  224. return 'soundcloud'
  225. elif 'youku.com' in link['domain']:
  226. return 'youku'
  227. elif 'vimeo.com' in link['domain']:
  228. return 'vimeo'
  229. return None
  230. def merge_links(a, b):
  231. """deterministially merge two links, favoring longer field values over shorter,
  232. and "cleaner" values over worse ones.
  233. """
  234. longer = lambda key: (a[key] if len(a[key]) > len(b[key]) else b[key]) if (a[key] and b[key]) else (a[key] or b[key])
  235. earlier = lambda key: a[key] if a[key] < b[key] else b[key]
  236. url = longer('url')
  237. longest_title = longer('title')
  238. cleanest_title = a['title'] if '://' not in (a['title'] or '') else b['title']
  239. link = {
  240. 'timestamp': earlier('timestamp'),
  241. 'url': url,
  242. 'domain': domain(url),
  243. 'base_url': base_url(url),
  244. 'tags': longer('tags'),
  245. 'title': longest_title if '://' not in (longest_title or '') else cleanest_title,
  246. 'sources': list(set(a.get('sources', []) + b.get('sources', []))),
  247. }
  248. link['type'] = get_link_type(link)
  249. return link
  250. def find_link(folder, links):
  251. """for a given archive folder, find the corresponding link object in links"""
  252. url = parse_url(folder)
  253. if url:
  254. for link in links:
  255. if (link['base_url'] in url) or (url in link['url']):
  256. return link
  257. timestamp = folder.split('.')[0]
  258. for link in links:
  259. if link['timestamp'].startswith(timestamp):
  260. if link['domain'] in os.listdir(os.path.join(ARCHIVE_DIR, folder)):
  261. return link # careful now, this isn't safe for most ppl
  262. if link['domain'] in parse_url(folder):
  263. return link
  264. return None
  265. def parse_url(folder):
  266. """for a given archive folder, figure out what url it's for"""
  267. link_json = os.path.join(ARCHIVE_DIR, folder, 'index.json')
  268. if os.path.exists(link_json):
  269. with open(link_json, 'r') as f:
  270. try:
  271. link_json = f.read().strip()
  272. if link_json:
  273. link = json.loads(link_json)
  274. return link['base_url']
  275. except ValueError:
  276. print('File contains invalid JSON: {}!'.format(link_json))
  277. archive_org_txt = os.path.join(ARCHIVE_DIR, folder, 'archive.org.txt')
  278. if os.path.exists(archive_org_txt):
  279. with open(archive_org_txt, 'r') as f:
  280. original_link = f.read().strip().split('/http', 1)[-1]
  281. with_scheme = 'http{}'.format(original_link)
  282. return with_scheme
  283. return ''
  284. def manually_merge_folders(source, target):
  285. """prompt for user input to resolve a conflict between two archive folders"""
  286. if not IS_TTY:
  287. return
  288. fname = lambda path: path.split('/')[-1]
  289. print(' {} and {} have conflicting files, which do you want to keep?'.format(fname(source), fname(target)))
  290. print(' - [enter]: do nothing (keep both)')
  291. print(' - a: prefer files from {}'.format(source))
  292. print(' - b: prefer files from {}'.format(target))
  293. print(' - q: quit and resolve the conflict manually')
  294. try:
  295. answer = input('> ').strip().lower()
  296. except KeyboardInterrupt:
  297. answer = 'q'
  298. assert answer in ('', 'a', 'b', 'q'), 'Invalid choice.'
  299. if answer == 'q':
  300. print('\nJust run ArchiveBox again to pick up where you left off.')
  301. raise SystemExit(0)
  302. elif answer == '':
  303. return
  304. files_in_source = set(os.listdir(source))
  305. files_in_target = set(os.listdir(target))
  306. for file in files_in_source:
  307. if file in files_in_target:
  308. to_delete = target if answer == 'a' else source
  309. run(['rm', '-Rf', os.path.join(to_delete, file)])
  310. run(['mv', os.path.join(source, file), os.path.join(target, file)])
  311. if not set(os.listdir(source)):
  312. run(['rm', '-Rf', source])
  313. def fix_folder_path(archive_path, link_folder, link):
  314. """given a folder, merge it to the canonical 'correct' path for the given link object"""
  315. source = os.path.join(archive_path, link_folder)
  316. target = os.path.join(archive_path, link['timestamp'])
  317. url_in_folder = parse_url(source)
  318. if not (url_in_folder in link['base_url']
  319. or link['base_url'] in url_in_folder):
  320. raise ValueError('The link does not match the url for this folder.')
  321. if not os.path.exists(target):
  322. # target doesn't exist so nothing needs merging, simply move A to B
  323. run(['mv', source, target])
  324. else:
  325. # target folder exists, check for conflicting files and attempt manual merge
  326. files_in_source = set(os.listdir(source))
  327. files_in_target = set(os.listdir(target))
  328. conflicting_files = files_in_source & files_in_target
  329. if not conflicting_files:
  330. for file in files_in_source:
  331. run(['mv', os.path.join(source, file), os.path.join(target, file)])
  332. if os.path.exists(source):
  333. files_in_source = set(os.listdir(source))
  334. if files_in_source:
  335. manually_merge_folders(source, target)
  336. else:
  337. run(['rm', '-R', source])
  338. def migrate_data():
  339. # migrate old folder to new OUTPUT folder
  340. old_dir = os.path.join(REPO_DIR, 'html')
  341. if os.path.exists(old_dir):
  342. print('[!] WARNING: Moved old output folder "html" to new location: {}'.format(OUTPUT_DIR))
  343. run(['mv', old_dir, OUTPUT_DIR], timeout=10)
  344. def cleanup_archive(archive_path, links):
  345. """move any incorrectly named folders to their canonical locations"""
  346. # for each folder that exists, see if we can match it up with a known good link
  347. # if we can, then merge the two folders (TODO: if not, move it to lost & found)
  348. unmatched = []
  349. bad_folders = []
  350. if not os.path.exists(archive_path):
  351. return
  352. for folder in os.listdir(archive_path):
  353. try:
  354. files = os.listdir(os.path.join(archive_path, folder))
  355. except NotADirectoryError:
  356. continue
  357. if files:
  358. link = find_link(folder, links)
  359. if link is None:
  360. unmatched.append(folder)
  361. continue
  362. if folder != link['timestamp']:
  363. bad_folders.append((folder, link))
  364. else:
  365. # delete empty folders
  366. run(['rm', '-R', os.path.join(archive_path, folder)])
  367. if bad_folders and IS_TTY and input('[!] Cleanup archive? y/[n]: ') == 'y':
  368. print('[!] Fixing {} improperly named folders in archive...'.format(len(bad_folders)))
  369. for folder, link in bad_folders:
  370. fix_folder_path(archive_path, folder, link)
  371. elif bad_folders:
  372. print('[!] Warning! {} folders need to be merged, fix by running ArchiveBox.'.format(len(bad_folders)))
  373. if unmatched:
  374. print('[!] Warning! {} unrecognized folders in html/archive/'.format(len(unmatched)))
  375. print(' '+ '\n '.join(unmatched))
  376. def wget_output_path(link, look_in=None):
  377. """calculate the path to the wgetted .html file, since wget may
  378. adjust some paths to be different than the base_url path.
  379. See docs on wget --adjust-extension (-E)
  380. """
  381. # if we have it stored, always prefer the actual output path to computed one
  382. if link.get('latest', {}).get('wget'):
  383. return link['latest']['wget']
  384. urlencode = lambda s: quote(s, encoding='utf-8', errors='replace')
  385. if link['type'] in ('PDF', 'image'):
  386. return urlencode(link['base_url'])
  387. # Since the wget algorithm to for -E (appending .html) is incredibly complex
  388. # instead of trying to emulate it here, we just look in the output folder
  389. # to see what html file wget actually created as the output
  390. wget_folder = link['base_url'].rsplit('/', 1)[0].split('/')
  391. look_in = os.path.join(ARCHIVE_DIR, link['timestamp'], *wget_folder)
  392. if look_in and os.path.exists(look_in):
  393. html_files = [
  394. f for f in os.listdir(look_in)
  395. if re.search(".+\\.[Hh][Tt][Mm][Ll]?$", f, re.I | re.M)
  396. ]
  397. if html_files:
  398. return urlencode(os.path.join(*wget_folder, html_files[0]))
  399. return None
  400. # If finding the actual output file didn't work, fall back to the buggy
  401. # implementation of the wget .html appending algorithm
  402. # split_url = link['url'].split('#', 1)
  403. # query = ('%3F' + link['url'].split('?', 1)[-1]) if '?' in link['url'] else ''
  404. # if re.search(".+\\.[Hh][Tt][Mm][Ll]?$", split_url[0], re.I | re.M):
  405. # # already ends in .html
  406. # return urlencode(link['base_url'])
  407. # else:
  408. # # .html needs to be appended
  409. # without_scheme = split_url[0].split('://', 1)[-1].split('?', 1)[0]
  410. # if without_scheme.endswith('/'):
  411. # if query:
  412. # return urlencode('#'.join([without_scheme + 'index.html' + query + '.html', *split_url[1:]]))
  413. # return urlencode('#'.join([without_scheme + 'index.html', *split_url[1:]]))
  414. # else:
  415. # if query:
  416. # return urlencode('#'.join([without_scheme + '/index.html' + query + '.html', *split_url[1:]]))
  417. # elif '/' in without_scheme:
  418. # return urlencode('#'.join([without_scheme + '.html', *split_url[1:]]))
  419. # return urlencode(link['base_url'] + '/index.html')
  420. def derived_link_info(link):
  421. """extend link info with the archive urls and other derived data"""
  422. link_info = {
  423. **link,
  424. 'date': datetime.fromtimestamp(Decimal(link['timestamp'])).strftime('%Y-%m-%d %H:%M'),
  425. 'google_favicon_url': 'https://www.google.com/s2/favicons?domain={domain}'.format(**link),
  426. 'favicon_url': 'archive/{timestamp}/favicon.ico'.format(**link),
  427. 'files_url': 'archive/{timestamp}/index.html'.format(**link),
  428. 'archive_url': 'archive/{}/{}'.format(link['timestamp'], wget_output_path(link) or 'index.html'),
  429. 'pdf_link': 'archive/{timestamp}/output.pdf'.format(**link),
  430. 'screenshot_link': 'archive/{timestamp}/screenshot.png'.format(**link),
  431. 'dom_link': 'archive/{timestamp}/output.html'.format(**link),
  432. 'archive_org_url': 'https://web.archive.org/web/{base_url}'.format(**link),
  433. 'title': link['title'] or link['url'],
  434. }
  435. # PDF and images are handled slightly differently
  436. # wget, screenshot, & pdf urls all point to the same file
  437. if link['type'] in ('PDF', 'image'):
  438. link_info.update({
  439. 'archive_url': 'archive/{timestamp}/{base_url}'.format(**link),
  440. 'pdf_link': 'archive/{timestamp}/{base_url}'.format(**link),
  441. 'screenshot_link': 'archive/{timestamp}/{base_url}'.format(**link),
  442. 'dom_link': 'archive/{timestamp}/{base_url}'.format(**link),
  443. 'title': link['title'] or basename(link['url']),
  444. })
  445. return link_info
  446. def run(*popenargs, input=None, capture_output=False, timeout=None, check=False, **kwargs):
  447. """Patched of subprocess.run to fix blocking io making timeout=innefective"""
  448. if input is not None:
  449. if 'stdin' in kwargs:
  450. raise ValueError('stdin and input arguments may not both be used.')
  451. kwargs['stdin'] = PIPE
  452. if capture_output:
  453. if ('stdout' in kwargs) or ('stderr' in kwargs):
  454. raise ValueError('stdout and stderr arguments may not be used '
  455. 'with capture_output.')
  456. kwargs['stdout'] = PIPE
  457. kwargs['stderr'] = PIPE
  458. with Popen(*popenargs, **kwargs) as process:
  459. try:
  460. stdout, stderr = process.communicate(input, timeout=timeout)
  461. except TimeoutExpired:
  462. process.kill()
  463. try:
  464. stdout, stderr = process.communicate(input, timeout=2)
  465. except:
  466. pass
  467. raise TimeoutExpired(popenargs[0][0], timeout)
  468. except BaseException as err:
  469. process.kill()
  470. # We don't call process.wait() as .__exit__ does that for us.
  471. raise
  472. retcode = process.poll()
  473. if check and retcode:
  474. raise CalledProcessError(retcode, process.args,
  475. output=stdout, stderr=stderr)
  476. return CompletedProcess(process.args, retcode, stdout, stderr)