程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

Python 中的一些命令行命令

hfteth 2025-03-06 15:26:03 技术文章 12 ℃

虽然 Python 通常用于构建具有图形用户界面 (GUI) 的应用程序,但它也支持命令行交互。

命令行界面 (CLI) 是一种基于文本的方法,用于与计算机的操作系统进行交互并运行程序。

从命令行运行 Python

可以直接从命令行运行 Python 脚本,方法是键入脚本文件名或路径目标。pyhton

python my_script.py

命令行解释器

Python 的解释器可以通过键入 .python

python

命令行参数

Python 允许您使用该模块解析命令行参数。argparse

import argparse

def main():
    parser = argparse.ArgumentParser(description='A simple command-line argument example')
    parser.add_argument('--input', required=True, help='Input file path')
    parser.add_argument('--output', required=True, help='Output file path')
    args = parser.parse_args()

    # Access the arguments
    input_file = args.input
    output_file = args.output

if __name__ == '__main__':
    main()

使用命令行参数运行脚本。

python my_script.py --input input.txt --output output.txt

外部命令

Python 允许您使用 module 执行外部命令。这对于自动执行任务或与其他命令行程序交互非常有用:subprocess

import subprocess

def run_command(command):
    result = subprocess.run(command, shell=True, capture_output=True, text=True)
    return result.stdout

if __name__ == '__main__':
    output = run_command('ls -l')
    print(output)
最近发表
标签列表