python

本文详细介绍了在Ubuntu系统中安装Python3.10,设置Python虚拟环境,管理requirements.txt,以及编写和运行Python程序,包括使用argparse模块和文件操作的示例。
摘要由CSDN通过智能技术生成

ubuntu安装python3:

ls /usr/bin/python* #能看到已有的python版本,若有即可不下
sudo apt install python3 python3-venv -y #会下载下来一个python3.10版本
sudo ln -sf python3.10 python3  #建立python3的软链接
python3 -V

虚拟环境:

python虚拟环境:
python3 -m venv venv	#创建虚拟环境
source venv/bin/activate	#进入虚拟环境
python -m pip install --upgrade pip	#更新环境内的软件包,类似apt update
pip list	#查看本环境安装了哪些包    
pip install -r requirements.txt  #批量安装,把模块提前写到requirements.txt
pip uninstall xxx -y	#卸载
chmod +x xx.py && ./xx.py #运行程序
deactivate  # 退出虚拟环境
rm -rf myvenv	#删除虚拟环境

requirements.txt示例:

numpy==1.21.0
pandas==1.3.3
matplotlib==3.4.3

python程序示例:

#!/usr/bin/env python3
import argparse
#from redisgarph import Graph as g  注意模块名千万不要重了

class MyClass: #每个成员函数第一个形参都是self
    def __init__(self, name, age): #构造函数
        self.name = name
        self.age = age

    def display(self):
        try: #try一般用于这个报错我们能接收,所以except: pass,否则就
            if self.age < 18 and self.name == 'hebin':
                pass
            elif self.age < 65:
                pass
            else:
                pass
        except:
            pass
        # except Exception as e: 
        #     print(e)
        #     exit()
        return 1

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-name', dest='name', default='gyl')
        parser.add_argument('-age', dest='age', type=int, required=True) #默认是str; required与default基本2选1 
    args = parser.parse_args()

    #创建对象
    my_object = MyClass(args.name, args.age)
    my_object.display()
    with open('1.txt', 'w') as f:
        f.write('xx')
    with open('1.txt', 'a') as f:#追加,是否加换行
        f.write('xx\n') 

常用命令

python3 -m http.server 默认8000端口

#!/usr/bin/env python3
import subprocess
import platform
import os
import glob

class Install:

    def __init__(self) -> None:
        self._machine = platform.machine()
        self._home_path = os.path.expanduser("~")
        self._current_path = os.path.abspath(os.path.dirname(__file__))
        self._dowload_path = os.path.join(self._current_path, "third_parties_repos")
        self._install_prefix = os.path.join(self._current_path, "third_parties")
        self._compile_prefix = os.path.join(self._current_path, "toolchain/aarch64--glibc--stable-final/bin/aarch64-buildroot-linux-gnu-")
        self._compile_cc = os.path.join(self._current_path, "toolchain/aarch64--glibc--stable-final/bin/aarch64-buildroot-linux-gnu-gcc")
        self._compile_ar = os.path.join(self._current_path, "toolchain/aarch64--glibc--stable-final/bin/aarch64-buildroot-linux-gnu-ar")
        self._compile_cxx = os.path.join(self._current_path, "toolchain/aarch64--glibc--stable-final/bin/aarch64-buildroot-linux-gnu-g++")
        self._compile_as = os.path.join(self._current_path, "toolchain/aarch64--glibc--stable-final/bin/aarch64-buildroot-linux-gnu-ranlib")
        self._compile_strip = os.path.join(self._current_path, "toolchain/aarch64--glibc--stable-final/bin/aarch64-buildroot-linux-gnu-strip")
        self._compile_sysroot = os.path.join(self._current_path, "toolchain/aarch64--glibc--stable-final/aarch64-buildroot-linux-gnu/sysroot")
        self._compile_pkg_libdir = os.path.join(self._current_path, "toolchain/aarch64--glibc--stable-final/usr/lib/pkgconfig")

        if not os.path.exists(self._install_prefix):
            os.makedirs(self._install_prefix)

    def start(self):
        #self._clone_opencv()
        #self._clone_protobuf()
        #self._clone_x264()
        #self._clone_ffmpeg()
        #self._clone_zmq()
        #self._clone_cpp_zmq()
        #self._clone_eigen()
        #self._clone_opengv()
        #self._clone_geographic()
        self._clone_pcl()

    def _clone_github_repo(self, repo_url, repo_name, *args):
        dowload_path = os.path.join(self._dowload_path, repo_name)
        if os.path.exists(dowload_path):
            print("repo exists: {}".format(dowload_path))
            return None
        command = "git clone {} {}".format(
            repo_url,
            dowload_path
        )
        for arg in args:
            command += " " + arg
        print("clone: {}".format(command))
        subprocess.run(command, shell=True)

    def _cmd(self, command):
        print("[command] {}".format(command))
        subprocess.run(command, shell=True)

    #https://docs.opencv.org/4.6.0/d2/dbc/cuda_intro.html
    #NVIDIA Corporation GA107M [GeForce RTX 3050 Mobile
    #Ubuntu: sudo apt install libgtk2.0-dev pkg-config GTK3.0
    def _clone_opencv(self):
        self._clone_github_repo(
            "https://github.com/opencv/opencv.git",
            "opencv",
            "--single-branch",
            "--branch=4.6.0",
            "--depth=1"
        )
        self._clone_github_repo(
            "https://github.com/opencv/opencv_contrib.git",
            "opencv_contrib",
            "--single-branch",
            "--branch=4.6.0",
            "--depth=1"
        )
        os.chdir("third_parties_repos/opencv")
        self._cmd("mkdir -p build")
        os.chdir("build")
        self._cmd("cmake \
                  -DCMAKE_TOOLCHAIN_FILE=../../../tools.cmake \
                  -DBUILD_SHARED_LIBS=ON \
                  -DBUILD_opencv_world=ON \
                  -DBUILD_TESTS=OFF \
                  -DBUILD_PREF_TESTS=OFF \
                  -DBUILD_EXAMPLES=OFF \
                  -DBUILD_opencv_apps=OFF \
                  -DWITH_GTK=ON \
                  -DWITH_IPP=OFF \
                  -DWITH_VIDEOIO=OFF \
                  -DWITH_FFMPEG=OFF \
                  -DWITH_GStreamer=OFF \
                  -DWITH_CUDA=OFF \
                  -DWITH_CUDNN=OFF \
                  -DOPENCV_DNN_CUDA=OFF \
                  -DCMAKE_INSTALL_PREFIX={} \
                  -DOPENCV_EXTRA_MODULES_PATH={} \
                  -DCMAKE_BUILD_TYPE=RELEASE ..".format(os.path.join(self._install_prefix, "opencv"), os.path.join(self._dowload_path, "opencv_contrib/modules/")))
        self._cmd("make install -j$(nproc)")
        os.chdir(self._current_path)

    def _clone_protobuf(self):
        self._clone_github_repo(
            "https://github.com/protocolbuffers/protobuf.git",
            "protobuf",
            "--single-branch",
            "--branch=v3.11.4",
            "--depth=1"
        )
        os.chdir(os.path.join(self._dowload_path, "protobuf"))
        os.chdir("cmake")
        self._cmd("mkdir -p build")
        os.chdir("build")
        self._cmd("cmake -DCMAKE_TOOLCHAIN_FILE=../../../tools.cmake -Dprotobuf_BUILD_SHARED_LIBS=ON -Dprotobuf_BUILD_TESTS=OFF -DCMAKE_INSTALL_PREFIX={} ..".format(os.path.join(self._install_prefix, "protobuf")))
        self._cmd("make install -j$(nproc)")
        os.chdir(self._current_path)

    def _clone_ffmpeg(self):
        self._clone_github_repo(
            "https://github.com/FFmpeg/FFmpeg.git",
            "ffmpeg",
            "--single-branch",
            "--branch=n3.2.16",
            "--depth=1"
        )
        os.chdir(os.path.join(self._dowload_path, "ffmpeg"))
        self._cmd("./configure --cross-prefix={} --enable-cross-compile \
                  --target-os=linux --arch=arm64 --enable-static --enable-shared \
                  --enable-libx264 --enable-gpl --prefix={} --disable-asm \
                  --extra-cflags=-I/home/cff/develop/orin/modules/third_parties/x264/include \
                  --extra-ldflags=-L/home/cff/develop/orin/modules/third_parties/x264/lib \
                  ".format(self._compile_prefix, os.path.join(self._install_prefix, "ffmpeg"))) #--enable-libx264 --enable-gpl
        self._cmd("make install -j$(nproc)")
        os.chdir(self._current_path)

    def _clone_x264(self):
        self._clone_github_repo(
            "https://code.videolan.org/videolan/x264.git",
            "x264",
            "--single-branch",
            "--branch=master",
            "--depth=1"
        )
        os.chdir(os.path.join(self._dowload_path, "x264"))
        self._cmd("./configure --prefix={} --enable-static --enable-shared --cross-prefix={} --disable-cli --disable-asm --host=aarch64-linux-gnu".format(os.path.join(self._install_prefix, "x264"), self._compile_prefix))
        self._cmd("make install -j$(nproc)")
        os.chdir(self._current_path)

    # Ref: https://sappo.github.io/2016/10/13/Cross-compiling-for-the-Raspberry-Pi/
    def _clone_zmq(self):
        self._clone_github_repo(
            "https://github.com/zeromq/libzmq.git",
            "zmq",
            "--single-branch",
            "--branch=master",
            "--depth=1"
        )
        os.chdir(os.path.join(self._dowload_path, "zmq"))
        # self._cmd("mkdir -p build")
        # os.chdir("build")
        # self._cmd("cmake \
        #           -DCMAKE_TOOLCHAIN_FILE=../../../tools.cmake \
        #           -DCMAKE_INSTALL_PREFIX={} \
        #           ..".format(os.path.join(self._install_prefix, "zmq")))
        self._cmd("./autogen.sh")
        self._cmd("./configure --prefix={} CC={} CXX={} AR={} RANLIB={} STRIP={} \
                  --build=x86_64-pc-linux-gnu \
                  --host=aarch64-linux --target=aarch64-linux --enable-static --without-libsodium \
                  PKG_CONFIG_LIBDIR={} \
                  PKG_CONFIG_SYSROOT={} \
                  ".format(os.path.join(self._install_prefix, "zmq"), self._compile_cc,
                           self._compile_cxx, self._compile_ar, self._compile_as, self._compile_strip,
                           self._compile_pkg_libdir, self._compile_sysroot))
        self._cmd("make install -j$(nproc)")
        os.chdir(self._current_path)

    def _clone_cpp_zmq(self):
        self._clone_github_repo(
            "https://github.com/zeromq/cppzmq.git",
            "cppzmq",
            "--single-branch",
            "--branch=master",
            "--depth=1"
        )
        os.chdir(os.path.join(self._dowload_path, "cppzmq"))
        self._cmd("mkdir -p build")
        os.chdir("build")
        self._cmd("cmake \
                  -DCMAKE_TOOLCHAIN_FILE=../../../tools.cmake \
                  -DCMAKE_INSTALL_PREFIX={} \
                  -DCPPZMQ_BUILD_TESTS=OFF \
                  ..".format(os.path.join(self._install_prefix, "zmq")))
        self._cmd("make install -j$(nproc)")
        os.chdir(self._current_path)

    #-DEIGEN_INCLUDE_DIRS=../../third_parties/eigen/include/eigen3 \
    def _clone_opengv(self):
        self._clone_github_repo(
            "https://github.com/laurentkneip/opengv.git",
            "opengv",
            "--single-branch",
            "--branch=master",
            "--depth=1"
        )
        os.chdir(os.path.join(self._dowload_path, "opengv"))
        self._cmd("mkdir -p build")
        os.chdir("build")
        self._cmd("cmake \
                  -DCMAKE_TOOLCHAIN_FILE=../../../tools.cmake \
                  -DEIGEN_INCLUDE_DIR=../../../third_parties/eigen/include/eigen3 \
                  -DCMAKE_INSTALL_PREFIX={} \
                  ..".format(os.path.join(self._install_prefix, "opengv")))
        self._cmd("make install -j$(nproc)")
        os.chdir(self._current_path)

    #cross comiple with warning TBD
    def _clone_eigen(self):
        self._clone_github_repo(
            "https://gitlab.com/libeigen/eigen.git",
            "eigen",
            "--single-branch",
            "--branch=3.4.0",
            "--depth=1",
            "--recursive"
        )
        os.chdir(os.path.join(self._dowload_path, "eigen"))
        self._cmd("mkdir -p build")
        os.chdir("build")
        self._cmd("cmake \
                  -DCMAKE_TOOLCHAIN_FILE=../../../tools.cmake \
                  -DCMAKE_INSTALL_PREFIX={} \
                  ..".format(os.path.join(self._install_prefix, "eigen")))
        self._cmd("make install -j$(nproc)")
        os.chdir(self._current_path)


    #v7.1.1/Rendering/Label: vtkLabelHierarchy.cxx:528和vtkLabelHierarchyPrivate.h:69,这2处不是const成员函数,导致编译失败
    def _clone_vtk(self):
        self._clone_github_repo(
            "https://gitlab.kitware.com/vtk/vtk.git",
            "vtk",
            "--single-branch",
            "--branch=v9.1.0",
            "--depth=1",
            "--recursive"
        )
        os.chdir(os.path.join(self._dowload_path, "vtk"))
        os.makedirs("build", exist_ok=True)
        os.chdir("build")
        system = platform.system()
        if system == "Windows":
            self._cmd("cmake .. -DCMAKE_INSTALL_PREFIX={} -DBUILD_TESTING=OFF -Ax64 -DCMAKE_BUILD_TYPE=Release".format(os.path.join(self._install_prefix, "vtk")))
            self._cmd("cmake --build . --config Release")
            self._cmd("cmake --install . --config Release")
        elif system == "Linux":
            self._cmd("cmake .. -DCMAKE_INSTALL_PREFIX={} -DBUILD_TESTING=OFF -DCMAKE_BUILD_TYPE=Release".format(os.path.join(self._install_prefix, "vtk")))
            self._cmd("make -j4")
            self._cmd("make install")
        os.chdir(self._current_path)

    def _clone_boost(self):
        self._clone_github_repo(
            "https://github.com/boostorg/boost.git",
            "boost",
            "--single-branch",
            "--branch=boost-1.72.0",
            "--depth=1",
            "--recursive"
        )
        os.chdir(os.path.join(self._dowload_path, "boost"))
        system = platform.system()
        if system == "Windows":
            self._cmd("bootstrap.bat")
            self._cmd("b2 install --prefix={} variant=release".format(os.path.join(self._install_prefix, "boost")))
            for file_path in glob.glob(os.path.join(self._install_prefix + "/boost/lib", "**", "*-x32-*"), recursive=True):
                os.remove(file_path)
        elif system == "Linux":
            self._cmd("./bootstrap.sh")
            self._cmd("./b2 install --prefix={} variant=release link=shared -j4".format(os.path.join(self._install_prefix, "boost")))
        os.chdir(self._current_path)

    def _clone_Eigen(self):
        self._clone_github_repo(
            "https://gitlab.com/libeigen/eigen.git",
            "eigen",
            "--single-branch",
            "--branch=3.3.7",
            "--depth=1",
            "--recursive"
        )
        os.chdir(os.path.join(self._dowload_path, "eigen"))
        os.makedirs("build", exist_ok=True)
        os.chdir("build")
        system = platform.system()
        if system == "Windows":
            self._cmd("cmake .. -DCMAKE_INSTALL_PREFIX={} -Ax64 -DCMAKE_BUILD_TYPE=Release".format(os.path.join(self._install_prefix, "eigen")))
            self._cmd("cmake --build . --config Release")
            self._cmd("cmake --install . --config Release")
        elif system == "Linux":
            self._cmd("cmake .. -DCMAKE_INSTALL_PREFIX={} -DCMAKE_BUILD_TYPE=Release".format(os.path.join(self._install_prefix, "eigen")))
            self._cmd("make -j4")
            self._cmd("make install")
        os.chdir(self._current_path)

    def _clone_flann(self):
        self._clone_github_repo(
            "https://github.com/flann-lib/flann.git",
            "flann",
            "--single-branch",
            "--branch=1.9.1",
            "--depth=1",
            "--recursive"
        )
        os.chdir(os.path.join(self._dowload_path, "flann"))
        os.makedirs("build", exist_ok=True)
        os.chdir("build")
        system = platform.system()
        if system == "Windows":
            self._cmd("cmake .. -DCMAKE_INSTALL_PREFIX={} -Ax64 -DCMAKE_BUILD_TYPE=Release -DBUILD_PYTHON_BINDINGS=OFF -DBUILD_MATLAB_BINDINGS=OFF -DBUILD_EXAMPLES=OFF -DBUILD_TESTS=OFF -DBUILD_DOC=OFF"\
                      .format(os.path.join(self._install_prefix, "flann")))
            self._cmd("cmake --build . --config Release")
            self._cmd("cmake --install . --config Release")
        elif system == "Linux":
            self._cmd("touch ../src/cpp/empty.cpp")
            cmd = "sed -i -e '32s/.*/add_library(flann_cpp SHARED \"empty.cpp\")/' -e '86s/.*/add_library(flann SHARED \"empty.cpp\")/' ../src/cpp/CMakeLists.txt"
            self._cmd(cmd)
            self._cmd("cmake .. -DCMAKE_INSTALL_PREFIX={} -DCMAKE_BUILD_TYPE=Release -DBUILD_PYTHON_BINDINGS=OFF -DBUILD_MATLAB_BINDINGS=OFF -DBUILD_EXAMPLES=OFF -DBUILD_TESTS=OFF -DBUILD_DOC=OFF"\
                      .format(os.path.join(self._install_prefix, "flann")))
            self._cmd("make -j4")
            self._cmd("make install")
        os.chdir(self._current_path)

    #pcl-1.9.0/segmentation/include/pcl/segmentation/supervoxel_clustering.h:528 相比1.10.0缺少判断,所以编译失败
    def _clone_pcl(self):
        self._clone_vtk()
        self._clone_boost()
        self._clone_Eigen()
        self._clone_flann()

        self._clone_github_repo(
            "https://github.com/PointCloudLibrary/pcl.git",
            "pcl",
            "--single-branch",
            "--branch=pcl-1.13.0",
            "--depth=1",
            "--recursive"
        )
        os.chdir(os.path.join(self._dowload_path, "pcl"))
        os.makedirs("build", exist_ok=True)
        os.chdir("build")
        cmake_prefix_path = self._install_prefix + "/vtk;" + self._install_prefix + "/boost;" + \
                    self._install_prefix + "/eigen;" + self._install_prefix + "/flann"
        system = platform.system()
        if system == "Windows":
            self._cmd("cmake .. -DCMAKE_PREFIX_PATH=\"{}\" -Ax64 -DCMAKE_BUILD_TYPE=Release".format(cmake_prefix_path))
            self._cmd("cmake --build . --config Release")
            self._cmd("cmake --install . --config Release --prefix={}".format(os.path.join(self._install_prefix, "pcl")))
        elif system == "Linux":
            self._cmd("cmake .. -DCMAKE_PREFIX_PATH=\"{}\" -DCMAKE_BUILD_TYPE=Release".format(cmake_prefix_path))
            self._cmd("cmake --build . --config Release -j4")
            self._cmd("cmake --install . --config Release --prefix={}".format(os.path.join(self._install_prefix, "pcl")))
        os.chdir(self._current_path)

    def _clone_geographic(self):
        self._clone_github_repo(
            "https://github.com/geographiclib/geographiclib.git",
            "geographiclib",
            "--single-branch",
            "--branch=v2.3",
            "--depth=1"
        )
        os.chdir(os.path.join(self._dowload_path, "geographiclib"))
        os.makedirs("build", exist_ok=True)
        os.chdir("build")
        system = platform.system()
        if system == "Windows":
            self._cmd('cmake .. -DCMAKE_INSTALL_PREFIX={} -DCMAKE_CXX_FLAGS_INIT=/utf-8 -DCMAKE_BUILD_TYPE=Release -Ax64'.format(os.path.join(self._install_prefix, "geographiclib")))
            self._cmd("cmake --build . --config Release")
            self._cmd("cmake --install . --config Release")
        elif system == "Linux":
            self._cmd("cmake .. -DCMAKE_INSTALL_PREFIX={} -DCMAKE_BUILD_TYPE=Release".format(os.path.join(self._install_prefix, "geographiclib")))
            self._cmd("make -j4")
            self._cmd("make install")
        os.chdir(self._current_path)


if __name__ == "__main__":
    install = Install()
    install.start()
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值