简体   繁体   中英

Escaping string arugments to subprocess calls in Windows

Why does Example one copy hello world to my clip board but not Example two ?

# Example one
subprocess.check_output(["echo", "hello world", "|", "clip"], shell=True, stderr=subprocess.STDOUT)

# Example two
subprocess.check_output(["echo", "hello \n world", "|", "clip"], shell=True, stderr=subprocess.STDOUT)

Another issues is that Example one copies hello world with quotes around it like so:

"hello world"

So, how do I copy text with multiple lines into the clipboard without double-quotes?

As suggested by @eryksun, this solves the issue:

p = subprocess.Popen('clip.exe', stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True)
p.communicate('hello \n world')
p.wait()

I suspect it's because you're using shell=True , refactor your code to not use it.

But I would suggest abandoning this approach alltogether and use pyperclip for the clipboard support. It's cross-platform and freely available.

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