subprocess call in python

2019-08-21 05:38发布

问题:

I need to execute the following command in terminal for multiple files SetFile -c "" -t "" <FileName> so I created a python script that would take filenames as arguments and use call function to execute the command. But I don't know how to put those "" marks in call pipe. here is the code

from subprocess import call
import sys # for sys.argv
def main():
    l = len(sys.argv)
    l = l - 1
    if(l>0):
        for i in range(l):
            termExecute(sys.argv[i])

def termExecute(argument):
    call(["SetFile", "-c ","","-t ","","argument"])

if __name__ == '__main__':
    main()

I am pretty sure the call(["SetFile", "-c ","","-t ","","argument"]) is wrong I hope to know the right way of writing it.

edit:

Akuls-MacBook-Pro:~ akulsanthosh$ python3 /Users/akulsanthosh/Documents/Simple/Setfile.py /Volumes/akul/Stuff/1.jpg /Volumes/akul/Stuff/2.jpg /Volumes/akul/Stuff/3.jpg 
Invalid type or creator value: '""'
Invalid type or creator value: '""'
ERROR: File Not Found. (-43)  on file: argument 
Invalid type or creator value: '""'
Invalid type or creator value: '""'
ERROR: File Not Found. (-43)  on file: argument 
Invalid type or creator value: '""'
Invalid type or creator value: '""'
ERROR: File Not Found. (-43)  on file: argument

回答1:

call(["SetFile", "-c ",'""',"-t ",'""',"argument"])

Python treats both ' & " as valid string delimiters, thus this is possible. Even otherwise you can escape the quotes. In fact you've used string with ' delimits with '__main__' in your code.

After looking at the errors you're getting I would try the below
call(["SetFile", "argument"])



回答2:

According to the documentation, you can pass empty strings:

args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names). If passing a single string, either shell must be True (see below) or else the string must simply name the program to be executed without specifying any arguments.

You can also pass quotes: "''"