简体   繁体   English

Python命令行执行

[英]Python Command line execution

I am trying to rename a set of pdf files in my desktop using a simple python script. 我正在尝试使用简单的python脚本重命名桌面上的一组pdf文件。 I am somehow not very successful. 我不怎么成功。 My current code is : 我当前的代码是:

import os,subprocess
path = "/Users/armed/Desktop/"
for file in os.listdir(path)
    command = ['mv', '*.pdf' , 'test.pdf']    // mv Command to rename files to test.pdf
    subprocess.call(command)

The output i get for this code is 1 and the files are not renamed. 我为此代码得到的输出为1,并且文件未重命名。 The same command works when executed in the terminal. 在终端中执行相同的命令。 I am using a Mac (if that helps in any way) 我正在使用Mac(如果有任何帮助)

The same command works when executed in the terminal. 在终端中执行相同的命令。

Except it's not the same command. 除了它是一样的命令。 The code is running: 该代码正在运行:

'mv' '*.pdf' 'test.pdf'

but when you type it out it runs: 但是当您输入时,它会运行:

'mv' *.pdf 'test.pdf'

The difference is that the shell globs the * wildcard before executing mv . 不同之处在于,在执行mv之前,shell会通配*通配符。 You can simulate what it does by using the glob module. 您可以使用glob模块来模拟其功能。

Python is not going to expand the shell wildcard in the string by default. Python默认情况下不会在字符串中扩展shell通配符。 You can also do this without a subprocess. 您也可以不使用子过程来执行此操作。 But your code will lose all pdf files except the last one. 但是您的代码将丢失除最后一个以外的所有pdf文件。

from glob import glob
import os
path = "/Users/armed/Desktop/"
os.chdir(path)
for filename in glob("*.pdf"):
    os.rename(filename, "test.pdf")

But I'm sure that's not what you really want. 但是我敢肯定那不是您真正想要的。 You'll need a better destination name. 您需要一个更好的目的地名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM