[英]Execute a terminal command that takes an argument from terminal in python a 2.6 script
My environment uses Python 2.6 and I'm new to Python. 我的环境使用Python 2.6,并且是Python的新手。 I need to write a script that runs a file decoding command which takes several arguments from the command line.
我需要编写一个运行文件解码命令的脚本,该命令从命令行获取多个参数。 My problem is I can't parse arguments taken from the terminal to the file decoding command.
我的问题是我无法解析从终端到文件解码命令的参数。
For example if my program name is x.py and when i run "x.py Desktop/abc.txt" how can i pass Desktop/abc.txt as an argument to the cat command? 例如,如果我的程序名称是x.py,而当我运行“ x.py Desktop / abc.txt”时,如何将Desktop / abc.txt作为参数传递给cat命令?
import commands
import sys
a=open("b.txt","w")
a.write(commands.getoutput('cat sys.argv[1]'))
When i researched it seemed that the above program should work but it didn't. 当我研究时,似乎上述程序应该可以工作,但是没有。 Please help.
请帮忙。
You're mixing up the terminal commands and Python commands. 您正在混合使用终端命令和Python命令。 If you have a file called
abc.py
with the following code: 如果您有一个名为
abc.py
的文件, abc.py
包含以下代码:
import sys
print sys.argv[1]
And you run it with python abc.py arg1
, it should print out arg1
. 然后使用
python abc.py arg1
运行它,它应该打印出arg1
。
For a cleaner and easier to read way of using command-line arguments if you want to control things like make sure they are int
or allow multiple or whatever, I've had a lot of success using the argparse
module in Python - it's much easier to use than the sys.argv
style of parsing command-line arguments. 如果您想控制诸如确保它们为
int
或允许多个或其他内容之类的东西,那么使用命令行参数的方式更简洁易读,我在Python中使用argparse
模块取得了很多成功-轻松得多比使用sys.argv
样式解析命令行参数要使用。 Check out the official tutorial / docs here: https://docs.python.org/2/howto/argparse.html 在此处查看官方教程/文档: https : //docs.python.org/2/howto/argparse.html
您应该将commands.getoutput('cat sys.argv[1]')
更改为commands.getoutput('cat %s' % (sys.argv[1],))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.