简体   繁体   English

如何从Linux命令行输入到我的Python脚本中?

[英]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.

相关问题 如何在python文件中使用命令行调用可以工作的python脚本? - How do I call a python script that works using command line inside my python file? 如何在命令行上接受用户输入的python脚本而不是提示 - How do I accept user input on command line for python script instead of prompt 如何修改 python 脚本以使用外部文件作为命令行中的输入? - How do I modify a python script to use an external file as the input in the command line? 如何让我的python(2.5版)脚本在文件夹而不是命令行中运行jar文件? - How can I get my python (version 2.5) script to run a jar file inside a folder instead of from command line? 如何让linux在Python解释器中自动运行我的python脚本? - How do I get linux to automatically run my python script in the Python interpreter? 在python中,如何将列表中的数据输入到linux命令中? - In python, how do you input data from a list into a linux command? 如何从需要命令行输入的python脚本中导入 - How to import from a python script that requires command line input 如何运行我的 Python 脚本? 为什么命令行告诉我“没有这样的文件或目录”? - How do I run my Python script? Why does the command line tell me "no such file or directory"? 如何从 python 解释器命令行获取 python 脚本路径? - How can I get the python script path from a python interpreter command line? 我如何忽略python命令行输入中的空格 - How do i ignore the space in command line input in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM