AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / ubuntu / 问题 / 646876
Accepted
Lynob
Lynob
Asked: 2015-07-11 09:09:43 +0800 CST2015-07-11 09:09:43 +0800 CST 2015-07-11 09:09:43 +0800 CST

将文件名从 bash 传递给 python

  • 772

可以说我在一个文件夹中有 1000 个具有随机名称的 csv 文件test。我有一个 python 脚本script.py。我想写一个 bash 脚本来传递文件夹中每个文件的名称script.py然后运行它,因此 bash 脚本应该运行script.py1000 次,每次都使用不同的文件名,例如,第一次运行:

with open('records.csv','r') as in_file

下次运行

with open('vertigo.csv','r') as in_file

我知道我可以在 python 中完成它而无需像这样编写 bash 脚本

import glob
for filename in glob.glob('*.csv'):
   # script here

但我正在做一些测试,因此我想在 bash 中进行

bash
  • 5 5 个回答
  • 20323 Views

5 个回答

  • Voted
  1. Best Answer
    muru
    2015-07-11T09:19:31+08:002015-07-11T09:19:31+08:00

    使用sys.argv[1]以便从参数中获取文件名:

    import sys
    
    with open(sys.argv[1],'r') as in_file
    

    然后,您可以使用各种方法将文件名作为参数传递。例如,与find:

    find test/ -type f -name '*.csv' -exec /path/to/script.py {} \;
    
    • 6
  2. gertvdijk
    2015-07-11T16:39:01+08:002015-07-11T16:39:01+08:00

    使用的替代方法sys.argv是使用argparse. 如果您需要更多的命令行参数解析,这非常有帮助。

    #!/usr/bin/env python2
    
    import argparse
    
    def main(files):
        for f in files:
            print "Would do something with", f
    
    if __name__ == "__main__":
        parser = argparse.ArgumentParser()
        parser.add_argument('file', nargs='+', help='path to the file')
        args_namespace = parser.parse_args()
        args = vars(args_namespace)['file']
        main(args)
    

    通过 Bash 扩展我们的文件参数列表来运行它:

    $ ./script.py *.csv
    Would do something with file1.csv
    Would do something with file2.csv
    Would do something with file3.csv
    

    并“免费”提供内置帮助:

    $ ./script.py --help
    usage: script.py [-h] file [file ...]
    
    positional arguments:
      file        path to the file
    
    optional arguments:
      -h, --help  show this help message and exit
    
    • 3
  3. kos
    2015-07-11T09:17:47+08:002015-07-11T09:17:47+08:00

    你必须在 python 脚本中检索文件名才能工作:

    #!/bin/bash
    for f in *.csv; do
        python script.py "$f"
    done
    

    在一行中:

    for f in *.csv; do python script.py "$f"; done
    
    • 2
  4. Jacob Vlijm
    2015-07-11T10:27:01+08:002015-07-11T10:27:01+08:00

    扩展 muru 的回答:

    为什么不在你的 python 脚本中完成这一切?将脚本对文件的操作转换为函数,然后以目录 作为参数运行脚本:

    #!/usr/bin/env python3
    import os
    
    #--- your original script, transformed into a function
    def some_function(file):
        print(file)
    #---
    
    # The directory with your .csv files
    dr = sys.argv[1]
    
    for f in os.listdir(dr):
        file = dr+"/"+f
        some_function(file)
    

    或者更短一点:

    for f in os.listdir(dr):
        some_function(dr+"/"+f)
    

    或者,如果该目录还可能包含其他文件:

    for f in [f for f in os.listdir(dr) if f.endswith(".csv")]:
        some_function(dr+"/"+f)
    

    然后只需将目录作为参数运行它:

    python3 <script> <directory>
    
    • 2
  5. gertvdijk
    2015-07-11T16:28:18+08:002015-07-11T16:28:18+08:00

    使用sys.argvas 列表,提供所有单独的文件作为参数,并让您的 shell(例如 Bash)为您展开它。

    script.py好像:

    #!/usr/bin/env python2
    
    import sys
    
    def main(files):
        for f in files:
            print "Would do something with", f
    
    if __name__ == "__main__":
        files = sys.argv[1:]: # slices off the first argument (executable itself)
        main(files)
    

    像这样的文件树:

    .
    ├── file1.csv
    ├── file2.csv
    ├── file3.csv
    └── script.py
    
    0 directories, 4 files
    

    然后使其可执行:

    chmod +x script.py
    

    使用 shell 扩展的参数运行它:

    ./script.py *.csv
    

    输出:

    Would do something with file1.csv
    Would do something with file2.csv
    Would do something with file3.csv
    
    • 2

相关问题

  • 同时复制到两个位置

  • 如何在 shell 脚本中创建选择菜单?

  • 从 bash 迁移到 zsh [关闭]

  • bashrc 还是 bash_profile?

  • 备份 bash 脚本未压缩其 tarball

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    如何运行 .sh 脚本?

    • 16 个回答
  • Marko Smith

    如何安装 .tar.gz(或 .tar.bz2)文件?

    • 14 个回答
  • Marko Smith

    如何列出所有已安装的软件包

    • 24 个回答
  • Marko Smith

    无法锁定管理目录 (/var/lib/dpkg/) 是另一个进程在使用它吗?

    • 25 个回答
  • Martin Hope
    Flimm 如何在没有 sudo 的情况下使用 docker? 2014-06-07 00:17:43 +0800 CST
  • Martin Hope
    Ivan 如何列出所有已安装的软件包 2010-12-17 18:08:49 +0800 CST
  • Martin Hope
    La Ode Adam Saputra 无法锁定管理目录 (/var/lib/dpkg/) 是另一个进程在使用它吗? 2010-11-30 18:12:48 +0800 CST
  • Martin Hope
    David Barry 如何从命令行确定目录(文件夹)的总大小? 2010-08-06 10:20:23 +0800 CST
  • Martin Hope
    jfoucher “以下软件包已被保留:”为什么以及如何解决? 2010-08-01 13:59:22 +0800 CST
  • Martin Hope
    David Ashford 如何删除 PPA? 2010-07-30 01:09:42 +0800 CST

热门标签

10.10 10.04 gnome networking server command-line package-management software-recommendation sound xorg

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve