20
20
import traceback
21
21
import socket
22
22
import signal
23
+ try :
24
+ from shlex import quote as shell_quote
25
+ except ImportError :
26
+ from pipes import quote as shell_quote
23
27
24
28
from osgtest .library import osgunittest
25
29
@@ -496,10 +500,8 @@ def __format_command(command):
496
500
return result
497
501
498
502
499
- def __prepare_shell_argument (argument ):
500
- if re .search (r'\W' , argument ) or argument == '' :
501
- return "'" + re .sub (r"'" , r"'\''" , argument ) + "'"
502
- return argument
503
+ _devnull = open (os .devnull , "r+b" )
504
+
503
505
504
506
def __run_command (command , use_test_user , a_input , a_stdout , a_stderr , log_output = True , shell = False , timeout = None , timeout_signal = 'TERM' ):
505
507
global _last_log_had_output
@@ -514,10 +516,10 @@ def __run_command(command, use_test_user, a_input, a_stdout, a_stderr, log_outpu
514
516
except TypeError :
515
517
print ('Need list or tuple, got %s' % type (command ))
516
518
if use_test_user :
517
- command = ['runuser' , options .username , '-c' , ' ' .join (map (__prepare_shell_argument , command ))]
519
+ command = ['runuser' , options .username , '-c' , ' ' .join (map (shell_quote , command ))]
518
520
519
521
# Figure out stdin
520
- stdin = None
522
+ stdin = _devnull
521
523
if a_input is not None :
522
524
stdin = subprocess .PIPE
523
525
@@ -555,7 +557,8 @@ def __run_command(command, use_test_user, a_input, a_stdout, a_stderr, log_outpu
555
557
os .killpg (p .pid , timeout_signal )
556
558
os ._exit (0 )
557
559
558
- (stdout , stderr ) = p .communicate (a_input )
560
+ stdout , stderr = p .communicate (to_bytes (a_input ))
561
+ stdout , stderr = to_str (stdout ), to_str (stderr )
559
562
560
563
if timeout is not None :
561
564
if p .returncode >= 0 :
@@ -783,11 +786,23 @@ def run_fn_if_el_release_ok(*args, **kwargs):
783
786
return el_release_decorator
784
787
785
788
786
- try :
787
- unicode
788
- except NameError : # python 3
789
- unicode = str
789
+ def to_str (strlike , encoding = "latin-1" , errors = "backslashreplace" ):
790
+ """Turns a bytes into a str (Python 3) or a unicode to a str (Python 2)"""
791
+ if strlike is None :
792
+ return
793
+ if not isinstance (strlike , str ):
794
+ if str is bytes :
795
+ return strlike .encode (encoding , errors )
796
+ else :
797
+ return strlike .decode (encoding , errors )
798
+ else :
799
+ return strlike
790
800
791
801
792
- def is_string (var ):
793
- return isinstance (var , (str , unicode ))
802
+ def to_bytes (strlike , encoding = "latin-1" , errors = "backslashreplace" ):
803
+ """Turns a str into bytes (Python 3) or a unicode to a str (Python 2)"""
804
+ if strlike is None :
805
+ return
806
+ if not isinstance (strlike , bytes ):
807
+ return strlike .encode (encoding , errors )
808
+ return strlike
0 commit comments