简体   繁体   中英

How do I run a command with string formatting?

I am using the subprocess module to run a command in python. But the problem is that I also want to include a string (for a file name) in the command.

An example of what I want to do:

  from subprocess import call

  command = "cd/DirectoryName"

  call = [(command)]

In this specific example I want DirectoryName to be a variable determined by the user.

What I have tried to no avail:

  Desktop=raw_input()
  cmd="'cd %s'(Desktop/)"
  call([cmd])

Here's the error I get when I try to run these commands in the python shell.

    Chicken='Chicken'
    command = 'say %s' % (Chicken)
    print command
    say Chicken
    call([command])

    Traceback (most recent call last):
    File "/Applications/WingIDE.app/Contents/MacOS/src/debug/tserver/_sandbox.py", line 1,     in <module>
    # Used internally for debug sandbox under external interpreter
    File "/Library/Frameworks/EPD64.framework/Versions/7.2/lib/python2.7/subprocess.py", line 493, in call
    return Popen(*popenargs, **kwargs).wait()
    File "/Library/Frameworks/EPD64.framework/Versions/7.2/lib/python2.7/subprocess.py", line 679, in __init__
    errread, errwrite)
    File "/Library/Frameworks/EPD64.framework/Versions/7.2/lib/python2.7/subprocess.py", line 1228, in _execute_child
    raise child_exception
    OSError: [Errno 2] No such file or directory

Just tried this and it made the shell crash.

    Chicken="Chicken"
    print Chicken
    Chicken
    call[("say %s" % (Chicken)]

这不是字符串插值的工作方式。

cmd='cd %s' % (Desktop,)

First off,

cmd="'cd %s'(Desktop/)" 

Doesn't seem like it would "printf" the %s.

Maybe

cmd="'cd %s/'%(Desktop)"

But I still don't know if that will interpolate since it's inside a string can using the "call" function and a python command -- wouldn't that call it on the command line?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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