繁体   English   中英

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

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

我一直在尝试使用系统命令的输出将其用作下一部分命令的一部分。 但是,我似乎无法正确加入它,因此无法正确运行第二个命令。 使用的操作系统是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内置了所有这些功能,所以你可以在不产生任何子shell的情况下完成它...

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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM