Skip to content

Instantly share code, notes, and snippets.

@npinto
Created September 12, 2012 07:52
Show Gist options
  • Save npinto/3705034 to your computer and use it in GitHub Desktop.
Save npinto/3705034 to your computer and use it in GitHub Desktop.
Python shell interface is painful (subprocess, commands, etc.)
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment