3

I need to read the exit of a command (then I have to wait for it in sync way):

import subprocess
subprocess.call('ls ~', shell=True)

My problem is a path like this:

~/testing/;xterm;/blabla

How could I sanitize that string from user (allowing special characters from his language)?

import subprocess
subprocess.call('ls ~/testing/;xterm;/blabla', shell=True) # This will launch xterm

I found escapeshellcmd in PHP, but I didn't find anything in Python.

PS: It's not a duplicate of this:

Thanks in advance!

=======

1 Answer 1

4

Pass a list instead of a string. And remove shell=True to make the command are not run by shell. (You need to expand ~ yourself using os.path.expanduser)

import os
import subprocess

subprocess.call(['ls', os.path.expanduser('~') + '/testing/;xterm;/blabla'])

Side note: If you want to get list of filenames, you'd better to use os.listdir instead:

filelist = os.listdir(os.path.expanduser('~') + '/testing/;xterm;/blabla')
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, but I found this problem: without the shell=True, I can't get the exit of the command, filelist is always empty.
@costales, It's weird. Could you try this? filelist = os.listdir(os.path.join(os.path.expanduser('~'), 'testing', ';xterm;', 'blabla'))
I would use check_call unless you want to ignore non zero exit status
@falsetru, yes that is what I meant.
@falsetru: Thanks a lot! the os library is solving my issue :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.