[英]How can I use this bash test construct in Python?
I have a bash snippet I would like to port over to Python. 我有一个bash片段,我想移植到Python。 It finds where SVN is located and whether it is executable.
它查找SVN的位置以及是否可执行。
SVN=`which svn 2>&1`
if [[ ! -x $SVN ]]; then
echo "A subversion binary could not be found ($SVN)"
fi
Here is my current attempt in Python using the subprocess module: 这是我目前在Python中使用subprocess模块的尝试:
SVN = Popen('which svn 2>&1', shell=True, stdout=PIPE).communicate()[0]
Popen("if [[ ! -x SVN ]]; then echo 'svn could not be found or executed'; fi", shell=True)
This does not work because while I do have the location of SVN saved in the local namespace of Python, I can't access it from Popen. 这是行不通的,因为虽然我确实将SVN的位置保存在Python的本地名称空间中,但无法从Popen访问它。
I also tried combining into one Popen object: 我还尝试将其合并为一个Popen对象:
Popen("if [[ ! -x 'which svn 2>&1']]; then echo 'svn could not be found'; fi", shell=True)
But I get this error (and needless to say, looks very unwieldy) 但是我得到了这个错误(不用说,看起来非常笨拙)
/bin/sh: -c: line 0: syntax error near `;'
/bin/sh: -c: line 0: `if [[ ! -x 'which svn 2>&1']]; then echo 'svn could not be found'; fi'
Is there a Python version of the test construct "-x"? 是否有Python版本的测试结构“ -x”? I think that would be ideal.
我认为那将是理想的。 Other workarounds would be appreciated as well.
其他解决方法也将不胜感激。
Thanks 谢谢
This is the simplest solution: 这是最简单的解决方案:
path_to_svn = shutil.which('svn')
is_executable = os.access(path_to_svn, os.X_OK)
shutil.which
is new in Python 3.3; shutil.which
3.3中的新增功能; there's a polyfill in this answer . 这个答案中有一个polyfill。 You could grab the path from
Popen
too if you really want, but that's not necessary. 如果确实需要,您也可以从
Popen
那里抢走路径,但这不是必需的。
SVN = Popen('which svn 2>&1', shell=True, stdout=PIPE).communicate()[0]
str="if [[ ! -x " + SVN + " ]]; then echo 'svn could not be found or executed'; fi"
Popen(str, shell=True)
There is no need to use which, you can already try to run svn without parameters and if it works it means it's there. 无需使用它,您已经可以尝试在不带参数的情况下运行svn,并且如果它有效,则意味着它已经存在。
try:
SVN = subprocess.Popen('svn')
SVN.wait()
print "svn exists"
except OSError:
print "svn does not exist"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.