Kode.Error404 Kode.Error404 - 1 year ago 48
Linux Question

How to use the previous command output to use as a part of another command: python

I have been trying to use the output of a system command to use it as a part of the command in the next portion. However, I cannot seem to join it up properly and hence not being able to run the second command properly. The OS used is KALI LINUX and python 2.7

import commands, os, subprocess

os.system('mkdir -p ~/Desktop/TOOLS')
checkdir = commands.getoutput('ls ~/Desktop')

if 'TOOLS' in checkdir:
currentwd = subprocess.check_output('pwd', shell=True)
cmd = 'cp -R {}/RAW ~/Desktop/TOOLS/'.format(currentwd)
os.system('cd ~/Desktop/TOOLS')

The errors are:

cp: missing destination file operand after ‘/media/root/ARSENAL’
Try 'cp --help' for more information.
sh: 2: /RAW: not found

It seems that the reading of the first command is alright but it can't join with the RAW portion. I have read many other solutions, but they seem to be for shell scripting instead.

Aya Aya
Answer Source

Assuming you haven't called os.chdir() anywhere prior to the cp -R, then you can use a relative path. Changing the code to...

if 'TOOLS' in checkdir:
    cmd = 'cp -R RAW ~/Desktop/TOOLS'

...should do the trick.

Note that the line...

os.system('cd ~/Desktop/TOOLS')

...will not do what you expect. os.system() spawns a subshell, so it will just change the working directory for that process and then exit. The calling process's working directory will remain unchanged.

If you want to change the working directory for the calling process, use...