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

标签 python linux command-line command concatenation

我一直在尝试使用系统命令的输出,将其用作下一部分命令的一部分。但是,我似乎无法正确加入它,因此无法正确运行第二个命令。使用的操作系统是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()

关于python - 如何使用先前的命令输出作为另一个命令 : python 的一部分使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38039934/

相关文章:

Python csv 模块在 writer.writerow 处抛出 "Error: sequence expected"

c - 从 FIFO 读取/写入

python - 如何让progame只启动一个进程?

java - BCP 以代码 0 退出

python - 使用 pytest 模拟 psycopg2 的正确方法是什么?

python - QtUiTools.QUiLoader() 是否由于某种原因需要 QFile 作为输入?

python - 是否有可排序和可搜索的 Python 数据结构?

c - 如何像 ps -e 一样显示进程

command-line - 用于将TTF/OTF字体转换为SVG的命令行工具

java - Java 命令行参数中的空格在 Amazon 云中引发错误