[英]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. 我正在尝试在python脚本中的chmod等文件上执行命令。 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.
我想像这样执行脚本./addExecute.py等等其中什么是某些文件的名称。 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 .
还有Python字符串格式:%vs . .format 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.