python 一个终端代码片段,在mac上生成可启动的usb live CD,以运行类似ubuntu或debian的内容。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 一个终端代码片段,在mac上生成可启动的usb live CD,以运行类似ubuntu或debian的内容。相关的知识,希望对你有一定的参考价值。

This script is for mac users who want to throw together a bootable usb without hasling with a GUI. Most operating systems require that you take up the entire drive when you install the live CD onto the disk so I've found that this snippet does pretty much the entire job I need. For those who are inspecting the code, the `$dmg_path` variable is needed because for some reason macs quite often are known for sticking `.dmg` on the end of their generated disk images.

Note: You can get the `$usb_path` by using `diskutil list`.

```bash
iso_path="~/Downloads/ubuntu-15.10-desktop-amd64.iso" && \
usb_path="/dev/rdisk1" && \
img_path="${iso_path}.img" && \
dmg_path="${img_path}.dmg" && \
hdiutil convert -format UDRW -o $img_path $iso_path && \
diskutil unmountDisk /dev/disk1 && \
sudo dd if=$dmg_path of=$usb_path bs=1m
```
# -*- coding: utf-8 -*-
# @Author: Cody Kochmann
# @Date:   2016-09-11 10:23:56
# @Last Modified by:   Cody L. Kochmann
# @Last Modified time: 2016-09-11 12:41:56

from os import popen, listdir
from os.path import isfile
from time import sleep
import re

def bash(cmd):
    return popen(cmd).read()

def shortest_first(*args):
    # input: unlimited arguments that have a len
    # output: tupple of those args ordered by length
    return tuple(sorted(list(args), key=len))

def extract_disks(s):
    disk_regex=r'disk[0-9]{1,}'
    return list(set(re.findall(disk_regex, s)))

def scan_disks():
    sleep(1)
    return extract_disks(bash("diskutil list"))
    return [x[68:] for x in '\n'.join(bash("diskutil list").split('\n')[2:-1]).split('\n')]

def new_items(old_list,new_list):
    out=[]
    for i in new_list:
        if i not in old_list:
            out.append(i)
    return(out)

def prompt_for_number(lowest=0, highest=9):
    t=''
    error_string = 'Error: Please a number between {} and {}'.format(lowest,highest)
    first_number = lambda i: re.findall(r'[0-9]{1,}', i)[0]
    no_number = lambda i: len(first_number(i)) < 1
    while no_number(t):
        t=raw_input()
        if no_number(t):
            print error_string
        else:
            i=int(t)
            if i<lowest or i>highest:
                print error_string
    return int(t)

def user_list_select(choice_list):
    for i in range(len(choice_list)):
        print "{} - {}".format(i+1,choice_list[i])
    choice=choice_list[prompt_for_number()]

def iso_files_in_dir():
    out=[]
    for i in listdir('./'):
        if i.endswith(".iso"):
            out.append(i)
    return out

def confirm(prompt_string):
    prompt_string="{} (y or n) ".format(prompt_string)
    ask = lambda i: raw_input(i).lower()[0]
    answer = ask(prompt_string)
    while answer not in "yn":
        print "invalid response"
        answer = ask(prompt_string)
    return answer is "y"

detected_iso_files=iso_files_in_dir()

if len(detected_iso_files) > 1:
    print "choose which iso file you want"
    iso_path=user_list_select(detected_iso_files)
elif len(detected_iso_files) is 1:
    iso_path=detected_iso_files.pop()
else:    
    print "no iso files detected in this directory."
    exit()

iso_path="./{}".format(iso_path)

confirm("Do you want to install: {}".format(iso_path))

raw_input("Make sure the USB drive you want to install this on isn't plugged in.\n[ENTER] to continue")

first_scan = scan_disks()

raw_input("plug in the USB drive now and press enter")

second_scan = scan_disks()

differences = new_items(first_scan, second_scan)

if len(differences)>1:
    print "There were too many new disks added. Exiting now"
else:
    usb_path = differences.pop()

usb_path="/dev/{}".format(usb_path)

img_path = "{}.img".format(iso_path)
dmg_path = "{}.dmg".format(img_path)

setup_command="""
hdiutil convert -format UDRW -o {} {} && diskutil unmountDisk {} && sudo dd if={} of={} bs=1m
""".format(img_path, iso_path, usb_path, dmg_path, usb_path)

raw_input("About to install {} on {}\n[ENTER] to continue".format(iso_path, usb_path))

bash(setup_command)

previous_example="""
iso_path="~/Downloads/ubuntu-15.10-desktop-amd64.iso" && \
usb_path="/dev/disk1" && \
img_path="${iso_path}.img" && \
dmg_path="${img_path}.dmg" && \
hdiutil convert -format UDRW -o $img_path $iso_path && \
diskutil unmountDisk $usb_path && \
sudo dd if=$dmg_path of=$usb_path bs=1m
"""

以上是关于python 一个终端代码片段,在mac上生成可启动的usb live CD,以运行类似ubuntu或debian的内容。的主要内容,如果未能解决你的问题,请参考以下文章

Python项目打包成可执行的exe文件

python 用于在终端中运行的sublime text 3的简单代码片段制作工具

“pip install jq”在 Mac 和 Windows 上生成错误

把py文件编译成可执行文件

python :python打包成可运行文件app

如何将 Python 脚本封装成可执行文件