简体   繁体   中英

How do I get input from linux command line into my Python script?

I am trying to execute a command on a file such as chmod in a python script. How can I get the file name from command line to the script? I want to execute the script like so ./addExecute.py blah Where blah is the name of some file. The code I have is this:

#!/usr/bin/python
import sys
import os
file = sys.argv[1]
os.system("chmod 700 file")

I keep getting the error that it cannot access 'file' no such file or directory.

os.system("chmod 700 file")
                     ^^^^--- literal string, looking for a file named "file"

You probably want

os.system("chmod 700 " + file)
                       ^^^^^^---concatenate your variable named "file"

可能是这样的

os.system("chmod 700 %s" % file)
os.system("chmod 700 file")

file is not replaced by its value. Try this :

os.system("chmod 700 " + file)

BTW, you should check if the script was executed with parameters (you could have an error such as "list index out of range")

As pointed out by other answers, you need to place the value of the variable file instead. However, following the suggested standard, you should use format and state it like

os.system("chmod 700 {:s}".format(file))

Using

os.system("chmod 700 %s" % file)

is discouraged, cf. also Python string formatting: % vs. .format .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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