如何将上一个命令输出用作另一个命令的一部分:python

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

我一直在尝试使用系统命令的输出,将其用作下一部分命令的一部分。但是,我似乎无法正确加入它,因此无法正确 运行 第二个命令。使用的 OS 是 KALI LINUX 和 python 2.7

#IMPORTS
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(cmd)
    os.system('cd ~/Desktop/TOOLS')
    os.system('pwd')

错误是:

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

第一条命令的读取好像还可以,但是不能和RAW部分拼接。我已经阅读了许多其他解决方案,但它们似乎是针对 shell 脚本编写的。

假设您没有在 cp -R 之前的任何地方调用 os.chdir(),那么您可以使用相对路径。将代码更改为...

if 'TOOLS' in checkdir:
    cmd = 'cp -R RAW ~/Desktop/TOOLS'
    os.system(cmd)

...应该可以解决问题。

注意行...

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

...不会如您所愿。 os.system() 生成一个子 shell,因此它只会更改该进程的工作目录,然后退出。调用进程的工作目录将保持不变。

如果要更改调用进程的工作目录,请使用...

os.chdir(os.path.expanduser('~/Desktop/TOOLS'))

但是,Python 内置了所有这些功能,因此您可以在不生成任何子外壳的情况下执行此操作...

import os, shutil


# Specify your path constants once only, so it's easier to change
# them later
SOURCE_PATH = 'RAW'
DEST_PATH = os.path.expanduser('~/Desktop/TOOLS/RAW')

# Recursively copy the files, creating the destination path if necessary.
shutil.copytree(SOURCE_PATH, DEST_PATH)

# Change to the new directory
os.chdir(DEST_PATH)

# Print the current working directory
print os.getcwd()