简体   繁体   English

在python的sys.argv中加注星号

[英]Star in sys.argv in python

I am attempting to write a script that utilises sys.argv to wrap the scp command. 我正在尝试编写一个利用sys.argv来包装scp命令的脚本。 The idea, is that you will be able to run: pyscp folder/* host but if I run this script with those arguments: 这个想法是,您将能够运行: pyscp folder/* host但是如果我使用以下参数运行此脚本:

import sys

for arg in sys.argv:
    print arg

I get a list of all the folders inside folder : 我得到一个文件folder中所有文件夹的列表:

pyscp.py
folder/0
folder/1
folder/2
folder/3
folder/4
folder/5
folder/67
folder/8
folder/9
host

Assuming a UNIXoid operating system: The shell is expanding the * into the matching files. 假设使用UNIXoid操作系统:Shell将*扩展为匹配的文件。 Try to call your script like 尝试像这样调用脚本

pyscp "folder/*" host

The quotes keep the shell from interpreting the * character. 引号使外壳程序无法解释*字符。

If you do not escape the asterisk, the shell is performing filename expansion for you. 如果您不转义星号,则说明Shell正在为您执行文件名扩展。 The pattern including the asterisk becomes replaced with an alphabetically sorted list of file names matching the pattern before your Python program becomes executed. 在执行Python程序之前,包括星号在内的模式被替换为与该模式匹配的文件名的字母顺序列表。 You can prevent the shell from performing filename expansion using eg single quotes, ie 您可以使用例如单引号来防止外壳执行文件名扩展,即

pyscp 'folder/*' hostname

You can then do this yourself within Python using the glob module and control things the way you want it. 然后,您可以使用glob模块在Python中自己进行操作,并按所需方式控制事物。

The shell is expanding the file list for you. Shell正在为您扩展文件列表。 You can leverage this by allowing multiple parameters in the command. 您可以通过在命令中允许多个参数来利用此功能。

import sys
files = sys.argv[1:-1]
host = sys.argv[-1]

Now you have a more flexible program that lets caller jump through whatever hoops he wants for the transfer, like maybe all text files in folder1 plus anything that's changed in the last day in folder2 (on a linux machine): 现在,您有了一个更灵活的程序,该程序可以使呼叫者跳过他要进行传输的任何条件,例如,文件夹1中的所有文本文件,以及文件夹2中最后一天发生的更改(在Linux计算机上):

pyscp folder1/*.txt `find -mtime -1` example.com

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM