python - 使用 subprocess.run() 在 python 中执行 shell 命令
问题描述
我有一个函数可以运行命令将所有文件从子文件夹移动到一个文件夹。
def move_images_to_one_folder(scr, dst):
if not os.path.exists(dst):
os.makedirs(dst)
print('Destination Created: ', dst)
cmd = 'find ' + \
os.path.join(scr) + ' -type f -print0 | xargs -0 mv -t ' + \
os.path.join(dst)
execute_cmd = run([cmd], stdout=subprocess.PIPE)
print(execute_cmd.stdout.read())
我不断收到文件不存在的错误。
FileNotFoundError: [Errno 2] No such file or directory: 'find /home/yury.stanev/Downloads/lfw-deepfunneled/ -type f -print0 | xargs -0 mv -t /home/yury.stanev/4nn3-project/clean_cnn_outputs/data/': 'find /home/yury.stanev/Downloads/lfw-deepfunneled/ -type f -print0 | xargs -0 mv -t /home/yury.stanev/4nn3-project/clean_cnn_outputs/data/'
我已经手动创建了目标文件夹并在bash
shell 中运行了命令,结果与预期一致,所有文件都已移动。我在函数中添加了一个条件来检查dst
文件夹并在不存在时创建它,但它似乎没有运行。
我怀疑这可能是路径的问题。造成这种情况的可能原因是什么,有解决办法吗?
解决方案
您cmd
的变量输入是单个字符串。如果要执行带有 的命令subprocess.run()
,则必须将所有用空格分隔的单独部分放入字符串列表中,如下所示:
execute_cmd = run(["find", os.path.join(scr), "-type", "f", "-print0", "|", "xargs", "-0", "mv", "-t", os.path.join(dst)], stdout=subprocess.PIPE)
推荐阅读
- javascript - excel javascript api加载项窗口窗格在默认浏览器中打开,而不是在窗口窗格中
- angular - 如何修复:无法连接到数据库MongoNetworkError
- django - 使用覆盖的 to_representation 更新嵌套序列化程序
- python - 根据名称列表创建对象和变量
- angular - Storybook with using Injection in angular module
- android - 展开/折叠工具栏拉动视图
- html - lottie 动画完全淡出
- lookup - 如何在查找 ax2012 中选择名称(或其他字段)而不是 ID
- javascript - 如何在chart.js中将`fillColor`作为渐变?
- angular - 如何覆盖 Angular 中现有组件的数据?