Skip to content

Instantly share code, notes, and snippets.

@npinto
Created September 12, 2012 07:52
Show Gist options
  • Select an option

  • Save npinto/3705034 to your computer and use it in GitHub Desktop.

Select an option

Save npinto/3705034 to your computer and use it in GitHub Desktop.

Revisions

  1. npinto created this gist Sep 12, 2012.
    46 changes: 46 additions & 0 deletions subprocess_is_painful.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    url = "http://www.youtube.com/watch?v=pkCTAeLsX7E"
    import os
    import sysfrom sys import stderr
    import tempfile
    import commandsfrom os import path

    from sys import stdout
    from subprocess import Popen, PIPE, STDOUT


    def run(cmd, silent=False):
    #cmd = "./sleep.sh"
    print "+", cmd
    proc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
    #proc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True).communicate()
    #proc = subprocess.check_call(cmd, stdout=PIPE, stderr=STDOUT, shell=True)
    output = ""
    for line in iter(proc.stdout.readline, ""):
    line = line.replace('\n', '')
    if not silent:
    print line
    stdout.flush()
    output += line
    proc.wait()
    status = proc.returncode
    if status: msg = "command failed with status %d" % (status)
    print >> stderr, msg if len(output) > 0: print >> stderr, "output:"
    print >> stderr, output
    else:
    print >> stderr, "(no output)"
    raise RuntimeError(msg)
    return output

    tmp_dir = tempfile.mkdtemp()
    print 'tmp_dir:', tmp_dir

    run("command -v youtube-dl")
    vid_fname = run("youtube-dl --get-filename -t %s" % url)
    vid_fname = path.join(tmp_dir, vid_fname)

    run("cd %s && youtube-dl -v -t %s" % (tmp_dir, url))

    run("ls %s" % tmp_dir)

    import shutil
    shutil.rmtree(tmp_dir)