Gezim
Gezim

Reputation: 7318

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?

Upvotes: 1

Views: 276

Answers (2)

Gezim
Gezim

Reputation: 7318

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()

Upvotes: 1

orlp
orlp

Reputation: 117741

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.

Upvotes: 0

Related Questions