【问题标题】:Subprocess in Python Add VariablesPython中的子进程添加变量
【发布时间】:2010-10-13 13:23:23
【问题描述】:

Python 中的子进程添加变量

import subprocess
subprocess.call('Schtasks /create /sc  ONCE  /tn  Work  /tr C:\work.exe /st 15:42 /sd 13/10/2010')

我希望能够在上述命令中设置变量。变量是在 15 和 42 中分隔的时间 '15:42' 以及在日、月和年中分隔的日期 '13/10/2010' 有什么想法吗??

提前感谢

乔治

【问题讨论】:

    标签: python string


    【解决方案1】:

    使用% formatting 构建命令字符串。

    >>> hour,minute = '15','42'
    >>> day,month,year = '13','10','2010'
    >>> command = 'Schtasks /create /sc  ONCE  /tn  Work  /tr C:\work.exe /st %s:%s /sd %s/%s/%s'
    >>> command % (hour,minute, day,month,year)
    'Schtasks /create /sc  ONCE  /tn  Work  /tr C:\\work.exe /st 15:42 /sd 13/10/2010'
    >>> subprocess.call( command % (hour,minute, day,month,year) )
    >>> 
    

    【讨论】:

    【解决方案2】:
    
    import subprocess 
    time = "15:42"
    date = "13/10/2010"
    # you can use these variables anyhow take input from user using raw_iput()
    subprocess.call('Schtasks /create /sc ONCE /tn Work /tr C:\work.exe /st '+time+' /sd '+date)
    

    【讨论】:

    • 如何制作时间和日期的字符串?
    • -1 通过对字符串求和来格式化字符串并不是唯一一种显而易见的方法。
    • @geocheats2 你可以使用日期时间的字符串是什么意思:docs.python.org/library/datetime.html 用于使用日期和时间对象以及字符串格式所需的方法是可能的
    【解决方案3】:

    Python 具有高级字符串格式化功能,对字符串使用 format 方法。例如:

    >>> template = "Hello, {name}. How are you today, {date}?"
    >>> name = "World"
    >>> date = "the fourteenth of October"
    >>> template.format(name=name, date=date)
    'Hello, World. How are you today, the fourteenth of October?'
    

    您可以在datetime 模块中使用strftime 获取时间和日期:

    >>> import datetime
    >>> now = datetime.datetime.now()
    >>> now.strftime("%A %B %Y, %I:%M:%S")
    'Wednesday October 2010, 02:54:30'
    

    【讨论】:

      【解决方案4】:
      import time
      
      subprocess.call(time.strftime("Schtasks /create /sc  ONCE  /tn  Work  /tr C:\work.exe /st %H:%M /sd %d/%m/%Y"))
      

      如果您想更改时间,可以将其设置为时间对象并使用它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-03
        • 2021-07-10
        • 2010-11-10
        • 2021-06-13
        • 1970-01-01
        • 2015-10-24
        • 2015-11-12
        • 2021-12-12
        相关资源
        最近更新 更多