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