【问题标题】:How do I run python script on specific folder如何在特定文件夹上运行 python 脚本
【发布时间】:2021-08-27 01:10:39
【问题描述】:

当我在终端中指定文件夹名称时,我正在尝试针对特定文件夹运行我的 python 脚本,例如

python script.py -'folder'

python script.py 'folder2'

“文件夹”是我想在其中运行脚本的 I 文件夹。是否有我必须使用的命令行开关?

【问题讨论】:

  • 我注意到您有很多老问题,答案很好,但没有被接受的答案。请查看并查看您是否可以接受其中一个答案,或者发布您自己的答案并接受。接受奖励回答者的努力,但也通过将已解决的问题标记为已解决来帮助未来的访问者,从而获得有用的答案。另见help.

标签: python python-3.x terminal command-line-interface


【解决方案1】:

shell 中的cd 命令切换您的当前目录。

或许也可以看看What exactly is current working directory?

如果您希望 Python 脚本接受目录参数,则必须自己实现命令行处理。在最简单的形式中,它可能看起来像

import sys

if len(sys.argv) == 1:
    mydir = '.'
else:
    mydir = sys.argv[1]

do_things_with(mydir)

通常,您可能会将其包装在 if __name__ == '__main__': 等中,并且可能接受多个目录并循环参数?

import sys
from os import scandir

def how_many_files(dirs):
    """
    Show the number of files in each directory in dirs
    """
    for adir in dirs:
        try:
            files = list(scandir(adir))
        except (PermissionError, FileNotFoundError) as exc:
            print('%s: %s' % (adir, exc), file=sys.stderr)
            continue
        print('%s: %i directory entries' % (adir, len(files)))

if __name__ == '__main__':
    how_many_files(sys.argv[1:] or ['.'])

【讨论】:

  • 感谢您的回复。但是我想要做的是针对我指定的子目录运行我的脚本..所以如果我想让脚本在文件夹 2 中运行,我只会放 $python script.py folder2
  • 这个答案的后半部分准确地解释了如何做到这一点。如果script.py 应该接受命令行参数,则需要从sys.argv 中获取它。当然,如果您不想自己做,也有第三方库可以提供帮助,但是如果没有额外的要求,很难特别推荐任何东西。
猜你喜欢
  • 2021-12-12
  • 2020-05-08
  • 2014-07-17
  • 2012-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-21
相关资源
最近更新 更多