【问题标题】:How to use the previous command output to use as a part of another command: python如何使用前面的命令输出作为另一个命令的一部分:python
【发布时间】:2016-10-28 15:21:11
【问题描述】:

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

【问题讨论】:

  • 有什么原因你不喜欢使用 Python 的 os.mkdir()os.listdir()os.getcwd()shutil.copytree()
  • @Aya 不是真的,但复制部分有一个文件夹,不是吗?因为 RAW 文件夹在 cwd 中。我需要以某种方式加入它。我也无法使用 os.listdir,因为我需要检查文件夹 TOOLS 是否已创建
  • @Kode.Error404> Aya 的观点是,鉴于所有文件操作都可以直接在 python 中轻松完成,尝试调用外部工具来完成它们是愚蠢的。而且性能较差。而且更容易出错。而且便携性较差。
  • @Kode.Error404> 例如,您可以只使用shutil.copytree('./RAW', '/home/some_user/Desktop/TOOLS') 就可以了。
  • 您可能想看看shutil 模块文档。它充满了对操作文件有用的功能。这比使用外部工具要容易得多。

标签: python linux command-line command concatenation


【解决方案1】:

假设您没有在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()

【讨论】:

  • 代码在您的回答中运行良好。即使现在一切正常,但仍然存在此错误。回溯(最后一次调用):文件“install.py”,第 14 行,在 os.chdir('~/Desktop/TOOLS') OSError: [Errno 2] No such file or directory: '~/Desktop /工具'
  • ...因为没有名为~的目录。
  • 我必须将其指定为 /root 吗?即使是一样的?
  • 什么意思是一样的? /root~ 不同。在你的shell中尝试touch '~',你会看到它创建了一个名为~的文件。
  • @Kode.Error404> 如果您打算按照常用约定将 ~ 扩展为用户主目录的别名,则可以使用 os.path.expanduser(path)
猜你喜欢
  • 2019-08-26
  • 1970-01-01
  • 1970-01-01
  • 2012-10-25
  • 2021-09-11
  • 2015-08-18
  • 1970-01-01
  • 2013-11-08
  • 1970-01-01
相关资源
最近更新 更多