Python 如何执行纯 shell 脚本

2018-05-23 09:13:53 +08:00
 wsds

查到的一些方法如 os.system(),os.popen(),os.exec() 等,都不是执行纯 shell 脚本啊,最简单的,我想通过 python 执行 shell,进入到某个文件夹中操作,该怎么操作?os.system("cd test sudo ./start.sh")没用啊

7478 次点击
所在节点    Python
34 条回复
wsds
2018-05-23 11:52:02 +08:00
@virusdefender 看上去很 6,学习一下
Qzier
2018-05-23 12:02:29 +08:00
试试

import subprocess

subprocess.call("[ -d Pic ] && { rm -r Pic ; mkdir Pic; } || mkdir Pic", shell=True)
wsds
2018-05-23 12:42:04 +08:00
@virusdefender 老铁,调不通啊,这个,是缩进不对吗?
TypeError: a bytes-like object is required, not 'str'

https://www.picb.cc/image/2bCbEa
extreme
2018-05-23 12:55:25 +08:00
virusdefender
2018-05-23 12:57:20 +08:00
@wsds #23 ...
natscat
2018-05-23 13:27:19 +08:00
@wsds #23 ...错误不已经报了么 类型不对。。。
araraloren
2018-05-23 16:58:19 +08:00
shell 脚本就是 bash/zsh/xsh 来执行的

#!/usr/bin/perl6
# your code goes here

my \bash = Proc::Async.new: "/usr/bin/env", "bash", :w;

react {
--whenever bash.stdout.lines {
----.say;
--}
--whenever bash.start { }
--whenever IN.lines {
----bash.say("s:g/^(\s+)/{ "--" x $0.codes }/; .say");
----bash.close-stdin if s:g/^(\s+)/{ "--" x $0.codes }/; .say eq "exit";
--}
}

try it online:  https://ideone.com/wvp1ue
araraloren
2018-05-23 17:00:58 +08:00
错了还不能改。。重新发一次 :(
#!/usr/bin/perl6
# your code goes here

my \bash = Proc::Async.new: "/usr/bin/env", "bash", :w;

react {
--whenever bash.stdout.lines {
----.say;
--}
--whenever bash.start { }
--whenever IN.lines {
----bash.say("$_");
----bash.close-stdin if $_ eq "exit";
--}
}
wsds
2018-05-23 19:13:46 +08:00
@virusdefender 怎么了老铁
alvin666
2018-05-23 19:30:26 +08:00
@wsds 哥,这水平劝你先学学英语,再学学 python,再来 v 站提问题吧。。。在这之前你的问题都可以问百度
noFound
2018-05-23 19:36:01 +08:00
os.popen("cd /tmp/test;sudo ./start.sh").read()
绝对路径和分号了解一下
ipwx
2018-05-23 19:56:51 +08:00
你先得确定 os.system 用了啥 shell。不一定是 bash
bao3
2018-05-23 20:48:43 +08:00
@ipwx 无所谓,后面强制使用 bash 执行就可以了。
wsds
2018-05-23 21:09:43 +08:00
@alvin666 不好意思,哥不会英语

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/457026

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX