Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass a long bash command to asyncio.subprocess.create_subprocess_exec()?

Right off the bat, there is a similar question here but it doesn't quite answer my question. I left a comment there just in case though.

In asyncio there is a asyncio.subprocess.create_subprocess_exec coroutine mimicking the more common subprocess.Popen command with shell=False to protect against shell injection. Popen accepts a list of strings but create_subprocess_exec only accepts strings, like

asyncio.subprocess.create_subprocess_exec('ls', '-lah', 'myfile', stdout=..., stderr=..., stdin=...)

I have a bash command as a big string, e.g. s = 'ls -lah myfile'. I want to pass the command to create_subprocess_exec but a list like s.split() doesn't work! How do?

like image 793
medley56 Avatar asked Feb 22 '26 20:02

medley56


1 Answers

It seems that asyncio.subprocess.create_subprocess_exec will accept a starred list as a series of arguments, so the solution should be

cmd = ['ls', '-lah', 'myfile']
asyncio.subprocess.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, stdin=asyncio.subprocess.PIPE)

A word of caution, formatting bash commands in this way can be difficult, especially with rsync I'm finding.

like image 65
medley56 Avatar answered Feb 25 '26 16:02

medley56



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!