查到的一些方法如 os.system(),os.popen(),os.exec() 等,都不是执行纯 shell 脚本啊,最简单的,我想通过 python 执行 shell,进入到某个文件夹中操作,该怎么操作?os.system("cd test sudo ./start.sh")没用啊
为什么没有卵用????
os.system("[ -d Pic ] && { rm -r Pic ; mkdir Pic; } || mkdir Pic")
1
yyttll 2018 年 5 月 23 日 |
2
ddrobot 2018 年 5 月 23 日
搜索“ python 切换目录”第一个搜索结果。。。os.chdir('/Users/<username>/Desktop/')
|
5
nongmei 2018 年 5 月 23 日
subprocess 了解一下
|
8
xia0chun 2018 年 5 月 23 日
直接用绝对路径不可以吗?
|
9
walleL 2018 年 5 月 23 日
应该是 cd test; 或者 cd test\n ?
|
10
xiaket 2018 年 5 月 23 日 这种问题我已经不知道该建议你先多学下 shell 还是先多学下 python 了...
|
14
shuizhengqi 2018 年 5 月 23 日
我第一次知道 shell 居然还有纯 shell 脚本一说
|
15
lieh222 2018 年 5 月 23 日
@wsds 你要先进一个目录在执行脚本其实是两条命令,bash 多条命令需要用;分隔,你执行的是脚本需要用 bash 执行,用./的话需要在脚本第一行申明解析器,os.system 不接受标准输入,所以你的密码输不进去,可以 sudo 执行 python 脚本,这里就不需要用 sudo 了
|
17
princelai 2018 年 5 月 23 日
pexpect,支持输入密码,等待加载等功能。subprocess.run()只支持一步操作,反正多个操作我没模拟成功
|
18
ClutchBear 2018 年 5 月 23 日
绝对路径就是了
|
19
cctv6 2018 年 5 月 23 日 via iPhone
&&
|
20
virusdefender 2018 年 5 月 23 日
def run_sh(command, strict=True):
cmd = [b"bash"] if strict: cmd.append(b"-e") return subprocess.run(cmd, input=command.encode("utf-8"), stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=strict) |
21
wsds OP @virusdefender 看上去很 6,学习一下
|
22
Qzier 2018 年 5 月 23 日
试试
import subprocess subprocess.call("[ -d Pic ] && { rm -r Pic ; mkdir Pic; } || mkdir Pic", shell=True) |
23
wsds OP @virusdefender 老铁,调不通啊,这个,是缩进不对吗?
TypeError: a bytes-like object is required, not 'str' https://www.picb.cc/image/2bCbEa |
24
extreme 2018 年 5 月 23 日
|
25
virusdefender 2018 年 5 月 23 日
@wsds #23 ...
|
27
araraloren 2018 年 5 月 23 日
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 |
28
araraloren 2018 年 5 月 23 日
错了还不能改。。重新发一次 :(
#!/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"; --} } |
29
wsds OP @virusdefender 怎么了老铁
|
32
ipwx 2018 年 5 月 23 日
你先得确定 os.system 用了啥 shell。不一定是 bash
|