0

I want to write a python script to execute to following line:

ls -1 -d ??? | cut -c 1-2 | sort | uniq | while read NN; do echo $NN; tar -cjf fcllistRPC_${NN}.bz2 ${NN}?; done

I tried:

def loop(jobname):
  """
  Loop over gen_fcl output and store as tarbull
  """
  loop = ["ls", "-1", "-d", "???", "|", "cut", "-c", "1-2", "|", "sort", "|", "uniq", "|", "while", "read", "NN;", "do", "echo", "$NN;", "tar", "-cjf", "fcllist_"+str(jobname)+".bz2", "${NN}?;", "done"]
  subproc = subprocess.run(loop)
  return subproc

But I am seeing this error:

ls: invalid option -- 'j'
Try 'ls --help' for more information.

Does anyone have any ideas?

Dave
  • 1
  • Can you make sure that the original command is the correct one? Can you run that one in your terminal? – Redowan Delowar May 09 '21 at 19:21
  • 1
    yes, it works, the idea is that I have a directory called 000 or 001 etc. and I want to tar all these up – Dave May 09 '21 at 19:22
  • 1
    `subprocess.run()` runs a *single* command - `ls` in your case, with about 20 parameters (most of which being things that `ls` doesn't understand). Generally, multiple commands require multiple `subprocess` calls - but that won't work in this case, since some parts of your command line (`while`, `read`) are inherently shell built-ins that *cannot* be run as standalone processes. The simplest solution would be to run the whole command (as a string, rather than a list), with `shell=True` so that the shell handles all of the individual commands for you. – jasonharper May 09 '21 at 19:34
  • None of this is hard to replace with native Python code. Write in shell script if you are not using Python's facilities anyway. – tripleee May 09 '21 at 19:36

1 Answers1

0

in your code you have -cjf. each letter is an "option" for a command. this is causing the error. if you remove it it will run

also if you want it to run a line of code then run that line of code.

codeToRun = "ls -1 -d ??? | cut -c 1-2 | sort | uniq | while read NN; do echo $NN; tar -cjf fcllistRPC_${NN}.bz2 ${NN}?; done"
subproc = subprocess.run(codeToRun)
a1cd
  • 17,884
  • 4
  • 8
  • 28