簡體   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